合并两个哈希以创建json文件

时间:2017-02-06 13:26:49

标签: ruby

您好我想将两个哈希合并到一个json文件中,该文件应如下所示:

{
 "name": "MS Suite",
 "version": "2017.1.0",
 "components": [
  {
   "code": "1x.2017",
   "name": "microservice1",
   "version": "1.1.3-1"
  },
  {
   "code": "3x.2017",
   "name": "microservice2",
   "version": "1.1.15-1"
  }
 ]
}

请在下面找到hash1:

{
 "name": "MS Suite",
 "version": "2017.1.0"
}

请在下面找到hash2,它是一个数组:

[
 {
  "code": "1x.2017",
  "name": "microservice1",
  "version": "1.1.3-1"
 },
 {
  "code": "3x.2017",
  "name": "microservice2",
  "version": "1.1.15-1"
 }
]

1 个答案:

答案 0 :(得分:2)

您正在寻找Hash#[]=

      JsonObject jsonObj;
      jsonObj.remove("test");

将其转换为json:

hash = {
  "name": "MS Suite",
  "version": "2017.1.0"
}


array = [
  {
    "code": "1x.2017",
    "name": "microservice1",
    "version": "1.1.3-1"
  },
  {
    "code": "3x.2017",
    "name": "microservice2",
    "version": "1.1.15-1"
  }
]

hash['components'] = array
hash
#=> {:name=>"MS Suite", :version=>"2017.1.0", "components"=>[{:code=>"1x.2017", :name=>"microservice1", :version=>"1.1.3-1"}, {:code=>"3x.2017", :name=>"microservice2", :version=>"1.1.15-1"}]}