Iterating over JSON in Rails

2020-06-29 06:59发布

问题:

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

Exploded out, it looks something like:

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

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

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.

回答1:

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

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"}}]}

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.