我正在尝试将JSON字符串附加到已有JSON数据的JSON文件中。
/public/temp.json:
fori
我想在此文件中添加新记录:
{
"IPBlock":"1.2.0.0/16,1.2.0.0/16,1.2.0.0/16,1.2.0.0/16",
"IPAddress":"1.2.3.4,1.2.3.5,1.2.3.6,1.2.128.1",
"device":"device1,device2,device3,device1"
}
我如何在Ruby中执行此操作?
答案 0 :(得分:1)
如果不先将JSON转换为Ruby Hash,就无法做到这一点。
current_json = JSON.parse('{
"IPBlock":"1.2.0.0/16,1.2.0.0/16,1.2.0.0/16,1.2.0.0/16",
"IPAddress":"1.2.3.4,1.2.3.5,1.2.3.6,1.2.128.1",
"device":"device1,device2,device3,device1"
}')
new_json = JSON.parse('{
"IPBlock":"1.2.0.0",
"IPAddress":"1.2.3.4",
"device":"device21"
}')
current_json.each do |key, value|
current_json[key] << ",#{new_json[key]}"
end
这会输出以下JSON:
{
"IPBlock": "1.2.0.0/16,1.2.0.0/16,1.2.0.0/16,1.2.0.0/16,1.2.0.0",
"IPAddress": "1.2.3.4,1.2.3.5,1.2.3.6,1.2.128.1,1.2.3.4",
"device": "device1,device2,device3,device1,device21"
}
有趣的是,每个JSON密钥的值都是逗号分隔的字符串。如果您的初始JSON值为arrays,则实际上只需将其附加到每个数组:
current_json.each do |key, value|
current_json[key] << new_json[key]
end
它还可以使您的代码和JSON数据更加清晰。