This trick with the jq 1.5 inputs streaming filter seems to do it

... | jq -n '.items |= [inputs]'

Ex.

$ find ~/ -maxdepth 1 -name "D*" | 
    while read line; do 
      jq -n --arg name "$(basename "$line")" \
            --arg path "$line" \
        '{name: $name, path: $path}'
    done | jq -n '.items |= [inputs]'
{
  "items": [
    {
      "name": "Downloads",
      "path": "/home/steeldriver/Downloads"
    },
    {
      "name": "Desktop",
      "path": "/home/steeldriver/Desktop"
    },
    {
      "name": "Documents",
      "path": "/home/steeldriver/Documents"
    }
  ]
}
Answer from steeldriver on Stack Exchange
🌐
GitHub
github.com › jqlang › jq › issues › 684
Creating an array from objects? · Issue #684 · jqlang/jq
January 29, 2015 - First of all, kudos on such an excellent library...I've used jq for basic CLI tasks and have only recently delved into its more advanced functions, and am continually amazed at how things just work with few surprises...rare for a CLI tool that has so many features... So I think my question is pretty basic, and I'm missing something very obvious that could be clarified in the docs. Given a series of objects, what do I pipe them through to get them into an array?
Author   dannguyen
🌐
Zendesk Developer Docs
developer.zendesk.com › documentation › integration-services › developer-guide › jq-cheat-sheet
jq cheat sheet | Zendesk Developer Docs
To create an array, wrap the output in square brackets ([]). The following expression combines the collaborator_ids and submitter_id properties into a single array. ... Use the index filter to get the index of the first occurrence of an element in an array. If the element doesn't exist in the ...
Discussions

bash - Add JSON objects to array using jq - Unix & Linux Stack Exchange
The jq that is being executed via -exec creates a JSON object per found pathname. It strips off everything in the pathname up to the last slash for the name value, and uses the pathname as is for the path value. The final jq reads the data from find into an array with -s, and simply inserts ... More on unix.stackexchange.com
🌐 unix.stackexchange.com
February 26, 2020
jq & bash: make JSON array from variable - Stack Overflow
I'm using jq to form a JSON in bash from variable values. ... But can't make arrays yet. More on stackoverflow.com
🌐 stackoverflow.com
bash - jq: output array of json objects - Stack Overflow
44 How to convert a JSON object stream into an array with jq More on stackoverflow.com
🌐 stackoverflow.com
bash - jq - create empty array and add objects to it - Stack Overflow
I am working on a bash script (using jq for JSON parsing) that needs to make multiple CURL calls (response has same structure but different values), apply some logic/filters and then collate all the More on stackoverflow.com
🌐 stackoverflow.com
🌐
iO Flood
ioflood.com › blog › jq-array
Manipulating JSON Arrays with jq | Example Guide
November 15, 2023 - In this example, we use the echo command to create an empty array, and then we use jq to add three elements to it: “Apple”, “Banana”, and “Cherry”. The '. += ["Apple", "Banana", "Cherry"]' part of the command is jq’s syntax for adding elements to an array. Accessing elements in an array is also simple in jq. Let’s access the second element (“Banana”) from our array:
🌐
Programming Historian
programminghistorian.org › en › lessons › json-and-jq
Reshaping JSON with jq | Programming Historian
May 24, 2016 - Both of these commands are wrapped in [] which tells jq to collect every result into one single array, which is passed with a | along to: join(";"), which turns that array into one single character string, with semicolon delimiters between multiple tweet ids. This filter created new JSON. To produce a CSV table from this, we just need to add an array construction and the @csv command at the end of this filter.
🌐
Exercism
exercism.org › tracks › jq › concepts › arrays
Arrays in jq on Exercism
The - operator removes elements in the right-hand array from the left-hand array. [range(10)] - [2, 4, 6] # => [0, 1, 3, 5, 7, 8, 9] jq provides many functions to cover common iteration functionality: map(expr) returns a new array where the expr is applied to each element in turn. [1, 2, 3] | map(. * 10) # => [10, 20, 30] select(expr) is a function that applies the expr to a single value; if the result of the expression is true, then the value is returned; if the result is false, nothing is returned -- not null, actually nothing.
Find elsewhere
🌐
jq recipes
remysharp.com › drafts › jq-recipes
jq recipes
April 16, 2024 - $ depcheck --json | jq ' .using | [ to_entries[] | select(.value[] | contains("/.next/")) | .key ] | unique | sort[] | "- \(.)" ' -r · Note: also uses depcheck to resolve the npm dependencies. ... Note that the walk function is missing from [email protected] and needs to be added (seen in demo). ... Bulk insert into elastic search using a vanilla JSON array, i.e.
🌐
jq
jqlang.org › manual
jq 1.8 Manual
Flush the output after each JSON object is printed (useful if you're piping a slow data source into jq and piping jq's output elsewhere). ... Parse the input in streaming fashion, outputting arrays of path and leaf values (scalars and empty arrays or empty objects).
🌐
Cht
cht.sh › jq
cheat.sh/jq
# Output a JSON file, in pretty-print format: jq # Output all elements from arrays # (or all key-value pairs from objects) in a JSON file: jq .[] # Use jq to pretty-print JSON jq '.' file.json # Filter JSON object by extracting a specific field jq '.fieldName' file.json # Filter JSON array to extract specific element by index jq '.[index]' file.json # Select multiple fields from JSON jq '{field1: .field1, field2: .field2}' file.json # Use jq to count the number of elements in an array jq '.arrayName | length' file.json # Apply a function to each element in a JSON array jq '.arrayName[] | .fiel
🌐
Earthly
earthly.dev › blog › jq-select
JQ Select Explained: Selecting elements from JSON with Examples - Earthly Blog
July 24, 2023 - This syntax is the same syntax for creating an object in a JSON document. The only difference is you can use the object and array queries you’ve built up as the values. Returning to my GitHub API problem, to wrap the number and the title up into an array I use the object constructor like this: $ curl https://api.github.com/repos/stedolan/jq/issues?per_page=2 | \ jq '[ .[] | { title: .title, number: .number} ]'
Top answer
1 of 5
33

We can solve this problem by two ways. They are:

Input string:

// test.json
{
    "keys": ["key1","key2","key3"]
}

Approach 1:

1) Use jq -r (output raw strings, not JSON texts) .

KEYS=$(jq -r '.keys' test.json)
echo $KEYS
# Output: [ "key1", "key2", "key3" ]

2) Use @sh (Converts input string to a series of space-separated strings). It removes square brackets[], comma(,) from the string.

KEYS=$(<test.json jq -r '.keys | @sh')
echo $KEYS
# Output: 'key1' 'key2' 'key3'

3) Using tr to remove single quotes from the string output. To delete specific characters use the -d option in tr.

KEYS=$((<test.json jq -r '.keys | @sh')| tr -d \') 
echo $KEYS
# Output: key1 key2 key3

4) We can convert the comma-separated string to the array by placing our string output in a round bracket(). It also called compound Assignment, where we declare the array with a bunch of values.

ARRAYNAME=(value1 value2  .... valueN)
#!/bin/bash
KEYS=($((<test.json jq -r '.keys | @sh') | tr -d \'\"))

echo "Array size: " ${#KEYS[@]}
echo "Array elements: "${KEYS[@]}

# Output: 
# Array size:  3
# Array elements: key1 key2 key3

Approach 2:

1) Use jq -r to get the string output, then use tr to delete characters like square brackets, double quotes and comma.

#!/bin/bash
KEYS=$(jq -r '.keys' test.json  | tr -d '[],"')
echo $KEYS

# Output: key1 key2 key3

2) Then we can convert the comma-separated string to the array by placing our string output in a round bracket().

#!/bin/bash
KEYS=($(jq -r '.keys' test.json  | tr -d '[]," '))

echo "Array size: " ${#KEYS[@]}
echo "Array elements: "${KEYS[@]}

# Output:
# Array size:  3
# Array elements: key1 key2 key3
2 of 5
16

To correctly parse values that may have newlines (and any other arbitrary (non-NUL) characters) use jq's @sh filter to generate space-separated quoted strings, and Bash's declare -a to parse the quoted strings as array elements. (No pre-processing required)

foo.json:

{"data": ["$0", " \t\n", "*", "\"", ""]}
str=$(jq -r '.data | @sh' foo.json)
declare -a arr="($str)"   # must be quoted like this
declare -p arr
# declare -a arr=([0]="\$0" [1]=$' \t\n' [2]="*" [3]="\"" [4]="")

Update: jq 1.7 (2023-09)

As of version 1.7, jq has a --raw-output0 option, enabling it to output null-terminated strings which can be read into an array as usual:

mapfile -d '' arr < <(jq --raw-output0 '.data[]' foo.json)
wait "$!"  # use in bash-4.4+ to get exit status of the process substitution

Note on NUL characters in JSON strings

JSON strings may contain NUL characters while shell variables cannot. If your JSON input may contain NUL's, you may need to add some special handling.

  • When using the @sh filter, NUL characters from JSON strings will be silently replaced with the sequence \0. Note that this makes the JSON strings "\\0" and "\u0000" indistinguishable.

  • When using the --raw-output0 option, NUL characters will trigger an error and jq will terminate with an exit status of 5.

Reading multiple/nested arrays

The @sh filter can be combined with --raw-output0 to reliably read multiple arrays at once (or a single nested array) as it will produce a NUL-separated list of space-separated quoted strings.

json='[[1,2],[3,4]]' i=0
while read -r -d ''; do
    declare -a "arr$((i++))=($REPLY)"
done < <(jq --raw-output0 '.[]|@sh' <<<$json)
for ((n=0; n<i; n++)); { declare -p "arr$n"; }
# declare -a arr0=([0]="1" [1]="2")
# declare -a arr1=([0]="3" [1]="4")
Top answer
1 of 4
24

jq has a flag for feeding actual JSON contents with its --argjson flag. What you need to do is, store the content of the first JSON file in a variable in jq's context and update it in the second JSON

jq --argjson groupInfo "$(<input.json)" '.[].groups += [$groupInfo]' orig.json

The part "$(<input.json)" is shell re-direction construct to output the contents of the file given and with the argument to --argjson it is stored in the variable groupInfo. Now you add it to the groups array in the actual filter part.

Putting it in another way, the above solution is equivalent of doing this

jq --argjson groupInfo '{"id": 9,"version": 0,"lastUpdTs": 1532371267968,"name": "Training" }' \
   '.[].groups += [$groupInfo]' orig.json
2 of 4
15

This is the exact case that the input function is for:

input and inputs [...] read from the same sources (e.g., stdin, files named on the command-line) as jq itself. These two builtins, and jq’s own reading actions, can be interleaved with each other.

That is, jq reads an object/value in from the file and executes the pipeline on it, and anywhere input appears the next input is read in and is used as the result of the function.

That means you can do:

jq '.[].groups += [input]' orig.json input.json

with exactly the command you've written already, plus input as the value. The input expression will evaluate to the (first) object read from the next file in the argument list, in this case the entire contents of input.json.

If you have multiple items to insert you can use inputs instead with the same meaning. It will apply across a single or multiple files from the command line equally, and [inputs] represents all the file bodies as an array.

It's also possible to interleave things to process multiple orig files, each with one companion file inserted, but separating the outputs would be a hassle.

🌐
Cameronnokes
cameronnokes.com › blog › jq-cheatsheet
JQ cheatsheet - Cameron Nokes
August 5, 2020 - -r gets rid of formatting like quotes and spaces for single values. For objects, it outputs valid JSON so it will have quotes. # this downloads the latest APOD and saves to a file url="https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY" curl -o apod.png "$(curl -s $url | jq -r '.hdurl')" ... Slices an array on by index. echo '["a", "b", "c", "d"]' | jq '.[1:3]' # ["b", "c"] Either the first or last index can be omitted to go from the begining or end.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-transform-json-data-with-jq
How To Transform JSON Data with jq | DigitalOcean
September 23, 2025 - In this step, you will generate a list of all sea creatures, using the creatures value to find their names. At the end of this step, you will have generated the following list of names: ... Generating this list requires extracting the names of the creatures and then merging them into an array. You’ll have to refine your filter to get the names of all creatures and discard everything else. Since you’re working on an array, you’ll need to tell jq you want to operate on the values of that array instead of the array itself.