user28374 user28374 - 1 year ago 62
Ruby Question

How to find and store all elements of a JSON array that have a certain key value pair

I am trying to parse JSON and extract some values to display.

The JSON format is:

"orders": [
"order_number": 12345,
"status" : "processing",

I have this sample response in JSON parsed in

response = http.request(request)
all_orders = JSON.parse(response.body)

# Checking for 'processing' orders...
processing_orders = all_orders["orders"].find{ |h| h['status'] == 'processing' }['order_number']

I want to display the matching
that have the status of 'processing', however when I enter:

puts "processing_orders"

it is only printing one value, when I know for certain that there are more.

Is there something I am doing wrong? I am fairly new to working with this and have tried my best to try solutions on my own.

Answer Source

Look at the documentation for the find method:

Passes each entry in enum to block. Returns the first for which block is not false.

Find will only return one entry.

You want to use something like select instead and then map to get the order number:

processing_orders = all_orders["orders"].select{ |h| h['status'] == 'processing'    }.map{|order| order['order_number']}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download