Iqen
Iqen

Reputation: 139

Filter through nested JSON object and obtain JSON with specific keys, using Ruby

I currently have a nested JSON object which resembles

{
"People": [
    {
        "Name": "James",
        "Age": "18",
        "Gender": "Male",
        "Sports": []
    },
    {
        "Name": "Sarah",
        "Age": "19",
        "Gender": "Female",
        "Sports": [
            "Soccer",
            "Basketball",
            "Football"
        ]
    }
] 
}

Being new to Ruby, I aim to filter throught the entire json and return only the json object/objects in which the "Sports" array has content. So in the above scenario I expect to obtain the object below as a final outcome:

    {
        "Name": "Sarah",
        "Age": "19",
        "Gender": "Female",
        "Sports": [
            "Soccer",
            "Basketball",
            "Football"
        ]
    }

Will I have to initiate a new method to perform such an act? Or would using regular ruby calls work in this case?

Upvotes: 2

Views: 1595

Answers (2)

dvxam
dvxam

Reputation: 604

Although @philipyoo answer is right, it miss an explanation on how to "filter" the parsed JSON. If you are new to ruby, take a look at Array#keep_if : http://ruby-doc.org/core-2.2.0/Array.html#method-i-keep_if

require 'json'

people = JSON.parse("{long JSON data ... }")
people_with_sports = people.fetch('People', []).keep_if do |person|
  !person.fetch('Sports', []).empty?
end

Upvotes: 2

philip yoo
philip yoo

Reputation: 2512

If you're getting a JSON object from a request, you want to parse it and then you can traverse the hash and arrays to find the information you need. See http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html

In your case, something like this:

require 'json'

parsed_json = JSON.parse('{"People": [ ... ]}')

parsed_json["People"].each do |person|
  puts person if person["name"] == "Sarah"
end

Upvotes: 2

Related Questions