Skip to main content

How do I parse this JSON output?

Rails • Asked by Stan Smith

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"=>"http://www.lacity.org/", "dbpedia"=>"http://dbpedia.org/resource/Los_Angeles", "freebase"=>"http://rdf.freebase.com/ns/m.030qb3t"}}, {"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"=>"http://dbpedia.org/resource/Betsey_Cushing_Roosevelt_Whitney", "freebase"=>"http://rdf.freebase.com/ns/m.06czgg", "yago"=>"http://yago-knowledge.org/resource/Betsey_Cushing_Roosevelt_Whitney"}}, {"type"=>"Person", "relevance"=>"0.290267", "count"=>"2", "text"=>"Emlen Etting", "disambiguated"=>{"name"=>"Emlen Etting", "dbpedia"=>"http://dbpedia.org/resource/Emlen_Etting", "freebase"=>"http://rdf.freebase.com/ns/m.0b6hzqr"}},


Hey Stan!

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

irb(main):002:0> @output.select{ |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.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.