Ask A Question


You’re not receiving notifications from this thread.

How do I parse this JSON output?

Stan Smith asked in Rails

I'm trying to extract the "text" element if the "type" is "Person" from this JSON output.
I''ve been able to store the JSON in an instance variable @output and am using the following to begin iterating it
<% @output.each do |item| %>
<%= item %>
<% end %>

But - stuck there.

Here's a sample of the JSON output:

[{"type"=>"Person", "relevance"=>"0.896887", "count"=>"14", "text"=>"Gloria Etting"}, {"type"=>"City", "relevance"=>"0.35271", "count"=>"4", "text"=>"Los Angeles", "disambiguated"=>{"subType"=>["GovernmentalJurisdiction", "OlympicBiddingCity", "OlympicHostCity", "PlaceWithNeighborhoods", "FilmScreeningVenue"], "name"=>"Los Angeles", "geo"=>"34.05 -118.25", "website"=>"", "dbpedia"=>"", "freebase"=>""}}, {"type"=>"City", "relevance"=>"0.347755", "count"=>"4", "text"=>"Philadelphia"}, {"type"=>"Person", "relevance"=>"0.32636", "count"=>"3", "text"=>"Betsey Cushing Roosevelt Whitney", "disambiguated"=>{"subType"=>["Collector"], "name"=>"Betsey Cushing Roosevelt Whitney", "dbpedia"=>"", "freebase"=>"", "yago"=>""}}, {"type"=>"Person", "relevance"=>"0.290267", "count"=>"2", "text"=>"Emlen Etting", "disambiguated"=>{"name"=>"Emlen Etting", "dbpedia"=>"", "freebase"=>""}},


Hey Stan!

You can do a pretty simple select and map to get the array of text strings here:

irb(main):002:0>{ |i| i["type"] == "Person" }.map{ |i| i["text"] }
=> ["Gloria Etting", "Betsey Cushing Roosevelt Whitney", "Emlen Etting"]

Basically the select filters the list, and map transforms the results from an array of hashes into an array of just the text attribute values. Then you can loop through that list and print them out in your erb.



Perfect. Thanks dude.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,969+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.