Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output the results of select operation in an array - jq

Tags:

bash

jq

I have the following input:

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

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

I get following as output :

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

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?

like image 895
user93726 Avatar asked Mar 15 '18 14:03

user93726


People also ask

What does jq return?

jq normally returns with exit code 0 if the jq program and and input data are valid, regardless of the program's output. Adding the -e flag causes jq to return with exit code 1 if the output is null or false and 0 otherwise.

What is jq slurp?

The slurp option ( -s ) changes the input to the jq program. It reads all the input values and build an array for the query input. Using with the raw input option ( -R ) means reading the entire input as a string. The inputs function is a special stream that emits the remaining JSON values given to the jq program.

What is a jq filter?

A jq program is a "filter": it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks.

What is jq query?

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed , awk , grep and friends let you play with text. jq is written in portable C, and it has zero runtime dependencies.


1 Answers

Yes; wrap the filter in an array :)

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

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

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

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}
like image 136
chepner Avatar answered Oct 18 '22 15:10

chepner