Use slurp mode:

  o   --slurp/-s:

      Instead of running the filter for each JSON object
      in the input, read the entire input stream into a large
      array and run the filter just once.
$ jq -s '.' < tmp.json
[
  {
    "name": "John",
    "email": "[email protected]"
  },
  {
    "name": "Brad",
    "email": "[email protected]"
  }
]
Answer from chepner on Stack Overflow
🌐
jq
jqlang.org › manual
jq 1.8 Manual
This option passes a JSON-encoded value to the jq program as a predefined variable. If you run jq with --argjson foo 123, then $foo is available in the program and has the value 123.
🌐
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 ... 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
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 array, the filter returns a null value.
🌐
Reddit
reddit.com › r/bash › more fun with jq, getting results into a usable array
r/bash on Reddit: More fun with jq, getting results into a usable array
August 17, 2024 -

I'm using this in a cURL to get the data from result[]:

foo=$(curl --request GET \
--silent \
--url https://example.com \
--header 'Content-Type: application/json' | jq -r '.result[]')

When I print $foo, this is what I have:

[key]
default

firewall_custom
zone
34
[
  {
    "id": "example",
    "version": "6",
    "action": "block",
    "expression": "lorem",
    "description": "ipsum",
    "last_updated": "2024-08-15T19:10:24.913784Z",
    "ref": "example",
    "enabled": true
  },
  {
    "id": "example2",
    "version": "7",
    "action": "block",
    "expression": "this",
    "description": "that",
    "last_updated": "2024-08-15T19:10:24.913784Z",
    "ref": "example2",
    "enabled": true
  }
]

What I need from this is to create a loop where, in a series of addtional cURLs, I can insert action, expression, and description.

I'm imagining that I would push these to 3 separate arrays (action, expression, and description), so that ${action[0]} would coincide with ${expression[0]} and ${description[0]}, and so on.

Something along the lines of:

# assuming that I have somehow created the following arrays:
# action=("block" "block")
# expression=("lorem" "this")
# description=("ipsum" "that")

for x in ${action[@]}; do
  bar=$(curl --request GET \
    --silent \
    --url https://example.com \
    --data '{
      "action": ${action[$x]},
      "expression": ${expression[$x]},
      "description": ${description[$x]}
    }' | jq '.success')

  if [[ $bar == true ]]
    then
      printf "$x succeeded\n"

    else
      printf "$x failed\n"
  fi

  # reset bar
  bar=''
done

The question is, how to create action, expression, and description arrays from the results of $foo (that original cURL)?

🌐
Exercism
exercism.org › tracks › jq › concepts › arrays
Arrays in jq on Exercism
Ready to put your newfound language skills into use? Get 40% off CodeCrafter's real-world proficiency projects! Claim your discount · Tracks · / jq · / Syllabus · / Arrays · Ar · 5 exercises · JSON defines an array as: An array is an ordered collection of values.
🌐
iO Flood
ioflood.com › blog › jq-array
Manipulating JSON Arrays with jq | Example Guide
November 15, 2023 - Creating an array in jq is straightforward. Let’s start with a simple example: echo '[]' | jq '. += ["Apple", "Banana", "Cherry"]' # Output: # ["Apple", "Banana", "Cherry"] 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.
Find elsewhere
🌐
Programming Historian
programminghistorian.org › en › lessons › json-and-jq
Reshaping JSON with jq | Programming Historian
May 24, 2016 - The results should now be just one line, as jq is now just returning one single JSON array: When jq returns just one JSON object, the ‘Compact Output’ option will produce a one-line result. If you want to access just the first (or the n-th) item in an array, put a digit in the [] operator:
🌐
Qmacro
qmacro.org › blog › posts › 2022 › 05 › 06 › converting-strings-to-objects-with-jq
Converting strings to objects with jq - DJ Adams
May 6, 2022 - Moreover, given that I had the elements where I wanted them, in an outer array, it would seem sensible at this point onwards to express the transformations required via map, which (like map in other languages, I guess it's as much of a paradigm as it is a function or filter), takes an array and produces an array. So for example, I could replace each string with its length, while still keeping the structure, by passing the [.,inputs] into map like this: ... This would produce the following (note I've used the --compact-output (-c) option to save space here): ... In the modification requirements, I first had to remove the SAP-samples/ organisation name prefix, and I turned to sub for that, as I'm partial to the occasional regular expression: jq -R '[.,inputs] | map(sub("^.+/";""))' names.txt
🌐
jq recipes
remysharp.com › drafts › jq-recipes
jq recipes
April 16, 2024 - echo "1\n2\n3" | jq --slurp --raw-input 'split("\n")[:-1]' ... Convert a plain list of timestamps to an array of objects with date and time separated (using jq's --slurp and --raw-input options combined):
🌐
Eliatra
eliatra.com › home › blog › transform json data on bash using jq
Transform JSON Data on Bash Using jq
November 23, 2022 - The output of this command is our original JSON array of objects but with the incremented “EmployedSince” field. Next, we pipe this output of jq back to jq, and tell it (again) that we are working with an arrays and want to extract the fields LastName, FirstName, and EmployedSince.
🌐
jq
jqlang.org › tutorial
Tutorial
If you want to get the output as a single array, you can tell jq to "collect" all of the answers by wrapping the filter in square brackets:
🌐
Baeldung
baeldung.com › home › files › file editing › how to add objects into json array using jq
How to Add Objects Into JSON Array Using jq | Baeldung on Linux
March 18, 2024 - In this tutorial, we’ll discuss how to add a JSON object to a JSON array in another file. For that purpose, we’ll make use of the jq utility.
🌐
Ingernet
ingernet.github.io › bash › jq › json › 2020 › 04 › 16 › json-array-bash-array.html
Converting a JSON array to a bash array
April 16, 2020 - # using gcloud output as a source because why not use the hardest shit possible bork=$(gcloud --project=<project-id> container images list-tags us.gcr.io/<project-id>/<image-name> --filter='tags:DEPLOYED' --format=json | jq '.[0].tags') echo $bork [ "260", "61a1d7aef75421f5c209c42304716ba44e86ab7a", "DEPLOYED.2019-11-12T17.04.37.772145800Z", "DEPLOYED.2019-11-13T00.00.29.525908800Z" ] # ^ output is obviously not a bash array # strip out all the things you don't want - square brackets and commas borkstring=$(echo $bork | sed -e 's/\[ //g' -e 's/\ ]//g' -e 's/\,//g') arr=( $borkstring ) echo $arr ( "260" "61a1d7aef75421f5c209c42304716ba44e86ab7a" "DEPLOYED.2019-11-12T17.04.37.772145800Z" "DEPLOYED.2019-11-13T00.00.29.525908800Z" ) # ^ now THAT is a bash array