【发布时间】:2017-03-28 08:13:05
【问题描述】:
我正在尝试动态创建 JSON 文件,其中每个文件的内容仅属于某个实体。
我有一个 Ruby 对象数组,其中每个对象代表一个实体。
entities = [#<Entity:0x0055f364d9cd78 @name="entity-B", @internal_asn_number=64514, @classification_id="B">,#<Entity:0x0055f364d89070 @name="entity-A", @internal_asn_number=64513, @classification_id="A">]
我有一个哈希数组,其中包含每个实体的多个规则,我想将这些哈希写入 JSON 文件,每个实体一个文件。
我有以下代码:
array_hashes = [{"rulename"=>"entity-B_source_fqdn_1", "if"=>{"source.fqdn"=>"mail.tec.dsr.entityB.com"}, "then"=>{"event_description.text"=>"B"}}, {"rulename"=>"entity-B_destination_fqdn_1", "if"=>{"destination.fqdn"=>"mail.tec.dsr.entity_B.com"}, "then"=>{"event_description.text"=>"B"}}, {"rulename"=>"entity-A_source_fqdn_1", "if"=>{"source.fqdn"=>"194-65-57-128.entityA.com"}, "then"=>{"event_description.text"=>"A"}}, {"rulename"=>"entity-A_destination_fqdn_1", "if"=>{"destination.fqdn"=>"194-65-57-128.entityA.com"}, "then"=>{"event_description.text"=>"A"}}]
path = "/home/mf370/Desktop/RubyProject/"
file_name = "_url_fqdn.conf"
entities.each do |entity|
File.open(path + entity.name + file_name, "w") do |f|
array_hashes.each do |rule|
if rule['rulename'].match(entity.name)
f.write(JSON.pretty_generate([rule]))
end
end
end
此代码工作并动态创建文件,但是文件的内容不是我所期望的。
这是上面代码的输出:
[
{
"rulename": "entity-A_source_fqdn_1",
"if": {
"source.fqdn": "194-65-57-128.entityA.com"
},
"then": {
"event_description.text": "A"
}
}
][
{
"rulename": "entity-A_destination_fqdn_1",
"if": {
"destination.fqdn": "194-65-57-128.entityA.com"
},
"then": {
"event_description.text": "A"
}
}
]
这是我正在寻找的输出:
[
{
"rulename": "entity-A_source_fqdn_1",
"if": {
"source.fqdn": "194-65-57-128.entityA.com"
},
"then": {
"event_description.text": "A"
}
},
{
"rulename": "entity-A_destination_fqdn_1",
"if": {
"destination.fqdn": "194-65-57-128.entityA.com"
},
"then": {
"event_description.text": "A"
}
}
]
可能这很容易解决,但我对如何解决这个问题没有想法,我是 Ruby 编程的新手。感谢您的帮助!
【问题讨论】: