所以我有这个代码读取文件并检查某个值,如果找到这些单词,关键字将被写入json文件。除了问题是它写了一个不必要的值。
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 :(得分:1)
First change $.post
to array, if you are not using index.php
as Hash in other places.
session_start();
$_SESSION = array();
session_unset();
session_destroy();
session_write_close();
session_regenerate_id(true);
Then while adding to the hosts do this, if you are interested in only hosts
, hosts
, hosts = []
and not :name
as key in file
:mac
Change writing logic to
:ip
Should see the expected data