在数组中输出选择操作的结果-JQ [英] Output the results of select operation in an array - jq

查看:98
本文介绍了在数组中输出选择操作的结果-JQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下输入内容:

[
  {"id": "first", "val": 1}, 
  {"id": "second", "val": 2}, 
  {"id": "second", "val": 3}
]

使用jq过滤器:.[] | select(.id =="second")

Using the jq filter : .[] | select(.id == "second")

我得到以下输出:

 {
  "id": "second",
  "val": 2
 }
 {
  "id": "second",
  "val": 3
 }

我想以数组形式获取结果.是否可以在数组中获得select操作的多个结果值?

I want to get the result in the form of an array. Is it possible to get the multiple result values of select operation in an array?

推荐答案

是;将过滤器包装在一个数组中:)

Yes; wrap the filter in an array :)

$ jq '[.[] | select(.id == "second")]' tmp.json
[
  {
    "id": "second",
    "val": 2
  },
  {
    "id": "second",
    "val": 3
  }
]

或者,使用预定义为[.[] | ...]map/1.

Or, use map/1, which is predefined as [.[] | ...].

$ jq 'map(select(.id == "second"))' tmp.json
[same result]


要将结果包装在bash数组中,请使用-c选项在一行上输出每个结果,并使用readarray读取结果.


To wrap the results in a bash array, use the -c option to output each result on a single line, and read the result with readarray.

$ readarray -t arr < <(jq -c '.[] | select(.id == "second")' tmp.json)
$ for r in "${arr[@]}"; do echo "Result: $r"; done
Result: {"id":"second","val":2}
Result: {"id":"second","val":3}

这篇关于在数组中输出选择操作的结果-JQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆