0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.