Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

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

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 29,763+ 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.