Ask A Question

Notifications

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"=>"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"}},

Reply

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.

🤘

Reply

Perfect. Thanks dude.

Reply
Join the discussion
Create an account Log in

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

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

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