J. Ballard
J. Ballard

Reputation: 49

Manipulating and Outputting JSON in Ruby

I have a JSON return (is it a hash? array? JS object?) where every entry is information on a person and follows the following format:

{"type"=>"PersonSummary", 
"id"=>"123", "properties"=>{"permalink"=>"personname", 
"api_path"=>"people/personname"}} 

I would like to go through every entry, and output only the "id"

I've put the entire JSON pull "response" into "result"

result = JSON.parse(response)

then, I'd like to go through result and do print the ID and "api_path" of the person:

result.each do |print id AND api_path|

How do I go about doing this in Ruby?

Upvotes: 0

Views: 85

Answers (1)

chemical
chemical

Reputation: 378

The only time you would need to use JSON.parse is if you have a string you need to parse into a Hash. For Example:

result = JSON.parse('{ "type" : "PersonSummary", "id" : 123, "properties" : { "permalink" : "personname", "api_path" : "people/personname" } }')

Once you have the Hash, result could be accessed by giving it the key, like result[:id] or result['id'] (both will work), or you can iterate through the hash too using the following code.

If you need to access the api_path value you would do so by using result['properties']['api_path']

result = { 'type' => 'PersonSummary', 'id' => 123, 'properties' => { 'permalink' => 'personname', 'api_path' => 'people/personname' } }

result.each do |key, value|
  puts "Key: #{key}\t\tValue: #{value}"
end

You could even do something like puts value if key == 'id' if you just want to show certain values.

Upvotes: 2

Related Questions