Ruby - iterate over parsed JSON
You're trying to iterate over data
, which is a hash, not a list. You need to get the children array from your JSON object by data['data']['children']
require "net/http"
require "uri"
require "json"
uri = URI.parse("http://www.reddit.com/user/brain_poop/comments/.json")
response = Net::HTTP.get_response(uri)
data = JSON.parse(response.body)
data['data']['children'].each do |child|
puts child['data']['body']
end
Iterating through a array of hashes in Ruby (parsed JSON)
Your code seems to lack i
variable (index) here, but actually you don't need it, since you can always use map
function to achieve idiomatic Ruby code:
require "json"
response = '{
"results": [
{
"zip": "08225",
"city": "Northfield",
"county": "Atlantic",
"state": "NJ",
"distance": "0.0"
},
{
"zip": "08221",
"city": "Linwood",
"county": "Atlantic",
"state": "NJ",
"distance": "1.8"
}
]
}'
parsed_response = JSON.parse(response)
zipcode_array = parsed_response["results"].map { |address| address["zip"] }
Iterate JSON with Ruby and get a key,value in an array
json = JSON.parse(your_json)
values = json.map { |_, v| { v[:PATH] => v[:ARTIFACTS].split(',') } }
You'll get the nice hash
{
'/tmp/pruebaAlvaro' => ['example1.jar', 'another_one.jar', ...],
'/tmp/pruebaAlvaro2' => [...]
}
And, you can iterate over it:
values.each do |path, artifacts|
artifacts.each do |artifact|
puts path
puts artifact
end
puts
end
You'll get the same output, which you provided in the question
How do I iterate over this JSON object?
Use JSON.parse to parse the response.
response = "{\"id\":\"a3adasfaf3\",\"url\":\"https://someurl/a3adasfaf3\",\"created\":\"2016-05-30T07:00:58Z\",\"modified\":\"2016-05-30T07:00:58Z\",\"files_hash\":\"cljhlk2j3l2kj34hlke18\",\"language\":\"ruby\",\"title\":\"Some weird hello world message\",\"public\":false,\"owner\":\"kljhlk2jh34lk2jh4l2kj3h4l2kj4h23l4kjh2l4k\",\"files\":[{\"name\":\"Some-weird-hello-world-message.rb\",\"content\":\"puts \\\"Some weird hello world message.\\\"\\r\\n\"}]}"
require 'json'
JSON.parse response
# output:
# {"id"=>"a3adasfaf3", "url"=>"https://someurl/a3adasfaf3", "created"=>"2016-05-30T07:00:58Z", "modified"=>"2016-05-30T07:00:58Z", "files_hash"=>"cljhlk2j3l2kj34hlke18", "language"=>"ruby", "title"=>"Some weird hello world message", "public"=>false, "owner"=>"kljhlk2jh34lk2jh4l2kj3h4l2kj4h23l4kjh2l4k", "files"=>[{"name"=>"Some-weird-hello-world-message.rb", "content"=>"puts \"Some weird hello world message.\"\r\n"}]}
response["name"] # => a3adasfaf3
how to iterate and retrive just the values from a json object with ruby
assuming you have the object as a string.
require 'json'
json_obj = '{"a" :"1", "b":"2", "c":"3"}'
values = JSON.parse(json_obj).values
will provide you with the array
["1", "2", "3"]
JSON.parse , parses the json string into a ruby object, in this case an instance of a Hash. The Hash class has a method values which returns an array containing the values or each hash entry.
Iterating over JSON in Rails
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.
How to iterate over this Json data in rails?
Four problems:
- you are not parsing the response body with
JSON.parse
- you are using a constant name (starting with capital letter) as a variable name (
@Response
), you shouldn't. - unnecessary
puts
on iteration. - The value of
data
is not an array, but rather another hash. So you should iterate over it as key/value pairs.
Solution:
@response = JSON.parse(HTTParty.get(your_url).body)
@response["data"].each do |key, value|
puts key
puts value
end
Ruby - Iterate over parsed json with no hash name
You will be given an Array
object when you parse that JSON string.
If you write the following code:
json.each do |release|
puts release['self']
end
You should see this output:
https://jira.company.com/rest/api/2/version/15685
https://jira.company.com/rest/api/2/version/15701
Ruby - Trying to iterate through a hash with a nested hash (after desieralising a JSON object)
You're trying to iterate over each value in the parsed JSON, which works in the same time because the value of rates
is a hash, but the values for base
and date
are strings. There you invoke each
and get the NoMethodError exception.
Try instead accessing the dates
key:
JSON.parse(json_string)['rates'].each do |currency, rate|
puts "#{currency} - #{rate}"
end
Related Topics
Homebrew Install: Failed During: Git Fetch Origin Master:Refs/Remotes/Origin/Master -N --Depth=1
Transforming Datetime into Month, Day and Year
Aws Elastic Beanstalk - How to Upgrade Existing Environment from Ruby 2.1 to Ruby 2.2
I Have a Gem Installed But Require 'Gemname' Does Not Work. Why
Put Haml Tags Inside Link_To Helper
Finding the Session Id in Rails 3
What Is '$:.Unshift File.Dirname(_File_)' Doing
What Does Post.All.Map(&:Id) Mean
Handling Namespace Models (Classes) in Namespace
How to Share Variables Across My .Rb Files
Getting the Highest Value of a Column in Mongodb
Create Array of N Items Based on Integer Value
Undef - Why Would You Want to Undefine a Method in Ruby
Why Is "Wsdl" Namespace Interjected into Action Name When Using Savon for Ruby Soap Communication
Scope of Constants in Ruby Modules
Visit_Psych_Nodes_Alias: Unknown Alias: Default (Psych::Badalias)