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.
JSON.parsewill convert your JSON string to a Ruby hash, so you can work with it as you would any other:There is a separate problem with your data, however. If you actually use
JSON.parsewith the data you posted, you should wind up with a result like this:You’ll notice there is only one continent – that’s because Ruby hashes only support one value per key, so the
Continentkey is being overwritten for eachContinentin the JSON. You might need to look at a different way of formatting that data.