在Ruby on Rails中从Deeply Nested JSON中提取数据

时间:2014-09-14 12:05:10

标签: ruby json ruby-on-rails-4

让Json像

一样出局
{
  "query": {
    "results": {
      "industry": [
        {
          "id": "112",
          "name": "Agricultural Chemicals",
          "company": [
            {
              "name": "Adarsh Plant",
              "symbol": "ADARSHPL"
            },
            {
              "name": "Agrium Inc",
              "symbol": "AGU"
            }
    },
    ]
    {
          "id": "914",
          "name": "Water Utilities",
          "company": [
            {
              "name": "Acque Potabili",
              "symbol": "ACP"
            },
            {
              "name": "Water Resources Group",
              "symbol": "WRG"
            }
          ]
        }
      ]
    }
  }
}

需要外出 - 公司名称,公司标志,公司ID, 公司ID名称

输出的例子是

Adarsh Plant,ADARSHPL,112,农业化学品 Agrium Inc,AGU,112,农业化学品 Acque Potabili,ACP,914,水务公用事业 水资源集团,WRG,914,水务公司

任何建议

1 个答案:

答案 0 :(得分:0)

你的样本json中有一个拼写错误,但我们稍后会谈论它。

假设您的json数据已经像这样转换为哈希对象:

json={
  "query"=> {
    "results"=> {
      "industry"=> [
        {
          "id"=> "112",
          "name"=> "Agricultural Chemicals",
          "company"=> [
            {
              "name"=> "Adarsh Plant",
              "symbol"=> "ADARSHPL"
            },
            {
              "name"=> "Agrium Inc",
              "symbol"=> "AGU"
            }
          ]
        },
       {    
          "id"=> "914",
          "name"=> "Water Utilities",
          "company"=> [
            {
              "name"=> "Acque Potabili",
              "symbol"=> "ACP"
            },
            {
              "name"=> "Water Resources Group",
              "symbol"=> "WRG"
            }
          ]
        }
      ]
    }
  }
}

你可以使用inject和map来处理行业的两级数组,inject会迭代外部数组:

json["query"]["results"]["industry"].inject([]){|m,o|
  m += o["company"].map{|x| [x["name"],x["symbol"],o["id"],o["name"]]}
}  

result是一个数组数组,其中包含您想要的顺序:

=> [["Adarsh Plant", "ADARSHPL", "112", "Agricultural Chemicals"], 
    ["Agrium Inc", "AGU", "112", "Agricultural Chemicals"], 
    ["Acque Potabili", "ACP", "914", "Water Utilities"], 
    ["Water Resources Group", "WRG", "914", "Water Utilities"]]

如果你想得到一个用逗号分隔的字符串,你最后可以在.flatten.join(",")上链接。

json["query"]["results"]["industry"].inject([]){|m,o|
  m += o["company"].map{|x| [x["name"],x["symbol"],o["id"],o["name"]]}
}.flatten.join(",") 

结果:

=> Adarsh Plant,ADARSHPL,112,Agricultural Chemicals,Agrium Inc,AGU,112,Agricultural Chemicals,Acque Potabili,ACP,914,Water Utilities,Water Resources Group,WRG,914,Water Utilities 

您的json数据的错字:

中间}, ] {应更改为] },{

将json转换为哈希

https://stackoverflow.com/a/7964378/3630826