在Rails中遍历JSON [英] Iterating over JSON in Rails

查看:94
本文介绍了在Rails中遍历JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单行JSON文件,我试图对其进行遍历,并寻找遍历该文件的最佳方法.

I have a single-line JSON file I'm trying to iterate over and looking for the best way to loop through it.

爆炸后,它看起来像:

{
 "system": "Test",
 "Continents": [
    {
        "Continent": {
            "name": "Europe",
            "location": "North"
         },
        "Continent": {
            "name": "Australia",
            "location": "South"
         },
        "Continent": {
            "name": "Asia",
            "location": "North"
         }
     }  
  ]
}

首先,我将使用以下内容加载JSON,这将成功加载完整的JSON.

To start, I'm loading in the JSON with the following, which successfully loads the full JSON.

File.open(json_file, 'r') do |file|

    file.each do |line|            

      JSON.parse(line).each do |item|

        ## CODE TO ITERATE HERE

      end        
    end
 end

我不确定该怎么做才能遍历Continents部分并提取关联的记录.目标是循环浏览并在列表/表/显示中输出信息.

What I'm not sure how to do is to loop through the Continents section and pull the associated records. The goal would be to loop through and output the info in a list/table/display.

感谢您的帮助-请让我知道是否可以澄清.

Thanks for the help - let me know if I can clarify at all.

推荐答案

JSON.parse会将您的JSON字符串转换为Ruby哈希,因此您可以像使用其他任何字符串一样使用它:

JSON.parse will convert your JSON string to a Ruby hash, so you can work with it as you would any other:

json = JSON.parse(line)
json["Continents"].each do |continent|
  # do something
end

但是,您的数据有一个单独的问题.如果您实际上对发布的数据使用JSON.parse,那么应该得到如下结果:

There is a separate problem with your data, however. If you actually use JSON.parse with the data you posted, you should wind up with a result like this:

{"system"=>"Test", "Continents"=>[{"Continent"=>{"name"=>"Asia", "location"=>"North"}}]}

您会注意到只有一个大陆-这是因为Ruby哈希每个键仅支持一个值,因此JSON中每个ContinentContinent键都被覆盖.您可能需要研究格式化数据的另一种方式.

You'll notice there is only one continent - that's because Ruby hashes only support one value per key, so the Continent key is being overwritten for each Continent in the JSON. You might need to look at a different way of formatting that data.

这篇关于在Rails中遍历JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆