Resolved this on github:

.[0] as $keys |
.[1] as $values |
reduce range(0; $keys|length) as $i  ( {}; . + { ($keys[values[$i] })
Answer from Abdullah Jibaly on Stack Overflow
🌐
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
Discussions

Create object from array of keys and values
I've been banging my head against the wall for several hours on this and just can't seem to find a way to do this. I have an array of keys and an array of values, how can I generate an obje... More on github.com
🌐 github.com
5
January 23, 2015
text processing - jq create object with property name from variable - Unix & Linux Stack Exchange
That is use the variable $n as the key, not the "$n" string. jq -n is like echo null | jq. ... Not using the {...} object constructor but assigning a value for a given key. More on unix.stackexchange.com
🌐 unix.stackexchange.com
October 5, 2024
json - How to use jq to create an object with an arbitrary key from a sub array? - Stack Overflow
I can also extract the categories with jq ' .things | .[] | .params | .[] | select(.key == "category") | .value' But I have not been able to combine them. ... Sign up to request clarification or add additional context in comments. ... I think you can shorten e.g. things | .[] to things[] 2019-01-21T07:27:01.02Z+00:00 ... Your params almost looks like key/value entries, so you could create an object out of them by passing the array to from... More on stackoverflow.com
🌐 stackoverflow.com
json - How to create object fields from array content using JQ - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
April 22, 2021
🌐
GitHub
github.com › jqlang › jq › issues › 675
Create object from array of keys and values · Issue #675 · jqlang/jq
January 23, 2015 - I've been banging my head against the wall for several hours on this and just can't seem to find a way to do this. I have an array of keys and an array of values, how can I generate an object. Input: [["key1", "key2"], ["val1", "val2"]] ...
Author   amjibaly
🌐
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 - Therefore, instead of nesting the array from posts.json into the posts array in blog.json, we used the $inputs[] notation. The $inputs[] construct effectively concatenates the contents of inputs as a flat array directly into posts in blog.json. This results in a single array. In this article, we explored the various ways we can add an object to a JSON array using jq.
Find elsewhere
🌐
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 - Similar to the array construction there's also the object construction, with which objects can be created on the fly quite easily. And as the manual says: If the keys are "identifier-like", then the quotes can be left off · So I can use name rather than "name" for the property, reducing the JSON noise a little: jq -R '[.,inputs] | map(sub("^.+/";"")) | map({name: .})' names.txt ... [ { "name": "cloud-sdk-js" }, { "name": "cloud-cap-samples-java" }, { "name": "btp-setup-automator" }, { "name": "btp-ai-sustainability-bootcamp" }, { "name": "cloud-cap-samples" }, { "name": "ui5-exercises-codejam" }, { "name": "cap-sflight" }, { "name": "cloud-cf-feature-flags-sample" }, { "name": "cloud-espm-cloud-native" }, { "name": "iot-edge-samples" } ]
🌐
Programming Historian
programminghistorian.org › en › lessons › json-and-jq
Reshaping JSON with jq | Programming Historian
May 24, 2016 - By wrapping . operators within either [] or {}, jq can synthesize new JSON arrays and objects. This can be useful if you want to output a new JSON file. As we will see below, this can also be a crucial intermediate step when reshaping complex JSON. Create a new set of JSON objects with the ...
Top answer
1 of 4
192

The |= .+ part in the filter adds a new element to the existing array. You can use jq with filter like:

jq '.data.messages[3] |= . + {
      "date": "2010-01-07T19:55:99.999Z", 
      "xml": "xml_samplesheet_2017_01_07_run_09.xml", 
      "status": "OKKK", 
      "message": "metadata loaded into iRODS successfullyyyyy"
}' inputJson

To avoid using the hardcoded length value 3 and dynamically add a new element, use . | length which returns the length, which can be used as the next array index, i.e.,

jq '.data.messages[.data.messages| length] |= . + {
      "date": "2010-01-07T19:55:99.999Z", 
      "xml": "xml_samplesheet_2017_01_07_run_09.xml", 
      "status": "OKKK", 
      "message": "metadata loaded into iRODS successfullyyyyy"
}' inputJson

(or) as per peak's suggestion in the comments, using the += operator alone

jq '.data.messages += [{
     "date": "2010-01-07T19:55:99.999Z",
     "xml": "xml_samplesheet_2017_01_07_run_09.xml", 
     "status": "OKKK", 
     "message": "metadata loaded into iRODS successfullyyyyy"
}]'

which produces the output you need:

{
  "report": "1.0",
  "data": {
    "date": "2010-01-07",
    "messages": [
      {
        "date": "2010-01-07T19:58:42.949Z",
        "xml": "xml_samplesheet_2017_01_07_run_09.xml",
        "status": "OK",
        "message": "metadata loaded into iRODS successfully"
      },
      {
        "date": "2010-01-07T20:22:46.949Z",
        "xml": "xml_samplesheet_2017_01_07_run_09.xml",
        "status": "NOK",
        "message": "metadata duplicated into iRODS"
      },
      {
        "date": "2010-01-07T22:11:55.949Z",
        "xml": "xml_samplesheet_2017_01_07_run_09.xml",
        "status": "NOK",
        "message": "metadata was not validated by XSD schema"
      },
      {
        "date": "2010-01-07T19:55:99.999Z",
        "xml": "xml_samplesheet_2017_01_07_run_09.xml",
        "status": "OKKK",
        "message": "metadata loaded into iRODS successfullyyyyy"
      }
    ]
  }
}

Use jq-play to dry-run your jq-filter and optimize any way you want.

2 of 4
79

Rather than using |=, consider using +=:

.data.messages += [{"date": "2010-01-07T19:55:99.999Z",
   "xml": "xml_samplesheet_2017_01_07_run_09.xml",
   "status": "OKKK", "message": "metadata loaded into iRODS successfullyyyyy"}]

Prepend

On the other hand, if (as @NicHuang asked) you want to add the JSON object to the beginning of the array, you could use the pattern:

 .data.messages |= [ _ ] + .
🌐
Stack Overflow
stackoverflow.com › questions › 62973375 › how-to-create-an-array-from-json-object-using-jq
how to create an array from json object using jq - Stack Overflow
[ .element1, .element2 # select properties element1 then element2 ] # wrapped in [] creates the array · In general, you could use this to gather all values of an object.
🌐
Zendesk Developer Docs
developer.zendesk.com › documentation › integration-services › developer-guide › jq-cheat-sheet
jq cheat sheet | Zendesk Developer Docs
The following expression extracts ... expr parameter, escape any double quotes with a leading backslash (\"). ... To create an array, wrap the output in square brackets ([])....
🌐
iO Flood
ioflood.com › blog › jq-array
Manipulating JSON Arrays with jq | Example Guide
November 15, 2023 - This guide will walk you through the ins and outs of working with arrays in jq, from basic operations to advanced techniques. We’ll cover everything from the creation, access, and modification of arrays to more complex operations like filtering, mapping, and reducing.
🌐
Cameronnokes
cameronnokes.com › blog › jq-cheatsheet
JQ cheatsheet - Cameron Nokes
August 5, 2020 - I wrote about jq in greater depth here. This is a cheatsheet of commands and function that I’ve found useful for quick reference. Common usages · Piping from curl · From a JSON file · In a chain of pipes · Common selectors · Get a named property · Get an array element by index · Get an array element’s property · Slice an array · Creating a new object ·
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.