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"
},
...
...
...
]
我已经尝试了各种东西,但我不能让对。
由于您自己在构建'hosts'哈希,为什么不以您需要的格式创建呢?或者您是否需要现在在代码的其他部分创建的格式? –