如何查找和存储具有特定键值对的JSON数组的所有元素

时间:2022-10-15 20:05:31

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

我试图解析JSON并提取一些值来显示。

The JSON format is:

JSON格式是:

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

I have this sample response in JSON parsed in all_orders:

我在all_orders中解析的JSON中有这个示例响应:

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 the status of 'processing', however when I enter:

我想显示状态为'processing'的匹配order_numbers,但是当我输入时:

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.

有什么我做错了吗?我是一个相当新的工作,并尽我所能尝试自己的解决方案。

1 个解决方案

#1


2  

Look at the documentation for the find method:

查看find方法的文档:

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

将枚举中的每个条目传递给块。返回第一个块不为false的块。

Find will only return one entry.

查找只返回一个条目。

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

你想使用像select这样的东西然后map来获取订单号:

processing_orders = all_orders["orders"].select{ |h| h['status'] == 'processing'    }.map{|order| order['order_number']}

#1


2  

Look at the documentation for the find method:

查看find方法的文档:

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

将枚举中的每个条目传递给块。返回第一个块不为false的块。

Find will only return one entry.

查找只返回一个条目。

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

你想使用像select这样的东西然后map来获取订单号:

processing_orders = all_orders["orders"].select{ |h| h['status'] == 'processing'    }.map{|order| order['order_number']}