2015-05-08 20 views
1

因此,我有这段代码读取一个文件并检查特定的值,如果它发现这些关键词将被写入到json文件中。除了问题是它写了一个不必要的值。ruby​​ json.pretty_generate输出

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 "]" 

这是输出我得到:

[ 
{ 
    "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" 
}, 
... 
... 
... 
] 

但希望输出为:

[ 
{ 
    "name" : "Mike" 
    "mac" : "a1:b2:c3:d4:e5:f6" 
    "ip" : "192.168.1.1" 
}, 
... 
... 
... 
] 

我已经尝试了各种东西,但我不能让对。

+0

由于您自己在构建'hosts'哈希,为什么不以您需要的格式创建呢?或者您是否需要现在在代码的其他部分创建的格式? –

回答

1

如果不在其他地方使用hosts作为散列,则首先将hosts更改为数组。

hosts = [] 

然后同时加入到主机做到这一点,如果你有兴趣只有:name:mac:ip而不是:host作为文件密钥

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

更改写作逻辑

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

应该看到预期的数据

+0

你先生,你是我的救星! – 5qFf3dmhkQ