Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

Filtering a nested json for a particular flied and returning adjacent member in ruby

I have an API response of the following structure

{
  "id": "123342-123412",
  "data": [
    {
      "id": "ace123",
      "name": "Tom",
      "files": [
        {
          "color": "yellow",
          "file_id": "245"
        },
        {
          "color": "red",
          "file_id": "233"
        }
      ]
    },
    {
      "id": "asd123",
      "name": "Jerry",
      "files": [
        {
          "color": "red",
          "file_id": "210"
        },
        {
          "color": "green",
          "file_id": "221"
        }
      ]
    },
    {
      "id": "acs123",
      "name": "Barbie",
      "files": [
        {
          "color": "green",
          "file_id": "201"
        }
      ]
    }
  ]
}

I am new to ruby, I want to filter out all file ids with the color red, what's the better way of doing it rather than iterating through the whole JSON using

data.each do  | object| 
# individual element search code 
end

I am using ruby version 2.6

question from:https://stackoverflow.com/questions/65875451/filtering-a-nested-json-for-a-particular-flied-and-returning-adjacent-member-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The single line version that comes to my mind is:

json[:data].map {|d| d[:files] }.flatten.select {|f| f[:color] == 'red' }.map {|f| f[:file_id] }
=> ["233", "210"]

But this iterates multiple times (one for every method call), not to mention it looks kind of cryptic to me.
Personally I would prefer a verbose version, where it's clearly stated how's getting the values:

file_ids = []
json[:data].each do |data| 
  data[:files].each do |file| 
    next if file[:color] != 'red'

    file_ids << file[:file_id]
  end
end
file_ids.uniq # In case you have duplicates

But is up to you what to use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...