2

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

This is just along the lines of what I'm looking for. However running this seems to retrieve a "undefined method 'fetch'" error. I've tried using 'map' or 'each do', and i get the same 'undefined method' error
Can you tell me the exact error? "undefined method error for XXX class". What is the XXX class? Can you give me more information about the content of people variable? My guess is that it is not a Hash. Maybe due to the JSON content.
Never mind. It was an error on my end. Your answer was exactly what I was looking for.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.