过滤后减少与 jq 不相加

Reducing after filtering doesn't add up with jq

我有以下数据:

[
  {
    "name": "example-1",
    "amount": 4
  },
  {
    "name": "foo",
    "amount": 42
  },
  {
    "name": "example-2",
    "amount": 6
  }
]

我想过滤 .name 包含“示例”的对象并减少 .amount 属性.

这是我尝试做的:

json='[{"name":"example-1","amount":4}, {"name": "foo","amount":42}, {"name": "example-2","amount":6}]'

echo $json | jq '.[] | select(.name | contains("example")) | .amount | add'

我收到这个错误:

jq: error (at :1): Cannot iterate over number (4)

我认为 .[] | select(.name | contains("example")) | .amount 的输出是一个流,而不是一个数组,所以我不能将这些值加在一起。

但是在 select 和查找之后,我怎么能改为输出数组呢?

我知道有一个 map 函数并且 map(.amount) | add 有效,但这里没有过滤。

之前没有.[] |我做不到select,我认为这就是“流”问题的来源...

正如您所说,add/0 需要一个数组作为输入。

因为它是一个有用的成语,请考虑使用 map(select(_)):

echo "$json" | jq 'map(select(.name | contains("example")) | .amount) | add'

但是,有时使用面向流的方法会更好:

def add(s): reduce s as $x (null; . + $x); 

add(.[] | select(.name | contains("example")) | .amount)