且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用jq根据内部数组中的值过滤对象数组?

更新时间:2023-01-17 19:11:59

非常接近!在select表达式中,必须在contains之前使用管道(|).

Very close! In your select expression, you have to use a pipe (|) before contains.

此过滤器产生预期的输出.

This filter produces the expected output.

. - map(select(.Names[] | contains ("data"))) | .[] .Id

jq食谱给出了语法示例.

根据键的内容过滤对象

例如,我只想要流派键包含"house"的对象.

Filter objects based on the contents of a key

E.g., I only want objects whose genre key contains "house".

$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]'
$ echo "$json" | jq -c '.[] | select(.genre | contains("house"))'
{"genre":"deep house"}
{"genre":"progressive house"}

Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.

最简单的方法是将整个表达式包装在数组构造函数中:

The simplest way is to wrap the whole expression in an array constructor:

$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]

您还可以使用地图功能:

You can also use the map function:

$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]

map解压缩输入数组,将过滤器应用于每个元素,然后创建一个新数组.换句话说,map(f)等同于[.[]|f].

map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f) is equivalent to [.[]|f].