user28374 user28374 - 8 months ago 19
JSON Question

Find and store all elements of a JSON array that have a certain key value pair (ruby)

I am trying to parse JSON and extract some values to display.
The JSON is of the structure:
"orders": [
"order_number": 12345,
"status" : "processing",

I have the following sample response in JSON parsed in all_orders.

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 order_numbers that have status '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. Thanks for any help!


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']}