so have code reads file , check value, if finds these words key-word written json file. except problem writes unnecessary value.
require 'json'  lines = io.readlines('dhcpd.conf') host = nil eth = nil address = nil  hosts = {}  lines.each |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 output 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 output be:
[  {    "name" : "mike"    "mac" : "a1:b2:c3:d4:e5:f6"    "ip" : "192.168.1.1"  }, ... ... ... ]   i have tried kinds of things, can't right.
first change hosts array, if not using hosts hash in other places.
hosts = []   then while adding hosts this, if interested in :name, :mac, :ip , not :host key in file
hosts << {name: host, mac: eth, ip: address}   change writing logic
file = file.new("new_computers.json", "w") file.puts json.pretty_generate(hosts)   should see expected data
Comments
Post a Comment