SO i have this code that reads a file and check for certain value, if it finds these words the key-word will be written to a json file. except the problem is that it writes an unnecessary value.
require 'json'
lines = IO.readlines('dhcpd.conf')
host = nil
eth = nil
address = nil
hosts = {}
lines.each do |line|
if line =~ /^host\s+(.+)\s+{$/
host = $1
eth = nil
address = nil
elsif line =~ /^\s*hardware ethernet (.*);$/
eth = $1
elsif line =~ /^\s*fixed-address (.*);$/
address = $1
elsif line =~ /^}$/
hosts[host] = {name: host, mac: eth, ip: address}
end
end
file = File.new("new_computers.json", "w")
file.puts "["
file.puts JSON.pretty_generate(hosts)
file.puts "]"
This is the output I get:
[
{
"Mike": {
"name": "Mike",
"mac": "a1:b2:c3:d4:e5:f6",
"ip": "192.168.1.1"
},
"Mike2": {
"name": "Mike2",
"mac": "aa:bb:cc:dd:ee:ff",
"ip": "192.168.1.2"
},
...
...
...
]
But want the output to be:
[
{
"name" : "Mike"
"mac" : "a1:b2:c3:d4:e5:f6"
"ip" : "192.168.1.1"
},
...
...
...
]
I have tried all kinds of things, but i can't get the right.
hostshash yourself, why not just create it in the format you need? Or do you need the format you are creating right now at some other part of the code?