JSON文件Ruby的哈希数组

时间:2017-03-28 08:13:06

标签: arrays json ruby hash

我试图动态创建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 Programming的新手。谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

问题是你将每个规则打包在一个数组中:

JSON.pretty_generate([rule])

您应该创建一个匹配rules的数组,并将其转储为JSON:

entities.each do |entity|
  File.open(File.join(path, entity.name + file_name), "w") do |f|
    matching_rules = array_hashes.select{ |rule| rule['rulename'].match(entity.name) }
    f.write(JSON.pretty_generate(matching_rules))
  end
end

答案 1 :(得分:-1)

问题是您将每个规则包装在一个数组中。 这应该解决问题:

json_entities = []
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)
                json_entities << rule
            end
        end
    end
end
f.write(JSON.pretty_generate(json_entities))