1

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.

1
  • Since you are building the hosts hash 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? Commented May 8, 2015 at 9:26

1 Answer 1

1

First change hosts to array, if you are not using hosts as Hash in other places.

hosts = []

Then while adding to the hosts do this, if you are interested in only :name, :mac, :ip and not :host as key in file

hosts << {name: host, mac: eth, ip: address}

Change writing logic to

file = File.new("new_computers.json", "w")
file.puts JSON.pretty_generate(hosts)

Should see the expected data

Sign up to request clarification or add additional context in comments.

1 Comment

You sir, you're my saviour!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.