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

json - Create object from array of keys and values - Stack Overflow
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? Inpu... More on stackoverflow.com
🌐 stackoverflow.com
bash - Add JSON objects to array using jq - Unix & Linux Stack Exchange
My goal is to output a JSON object using jq on the output of a find command in bash. It could either be a one-line command or a bash script. I have this command which creates JSON objects from eac... More on unix.stackexchange.com
🌐 unix.stackexchange.com
February 26, 2020
text processing - jq create object with property name from variable - Unix & Linux Stack Exchange
In an object constructor, when keys are to be the result of a jq expression, they must be inside (...). ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Polynomials whose roots are closed under a given function. Is it true that Iranian Scholars are excluded from ... More on unix.stackexchange.com
🌐 unix.stackexchange.com
October 5, 2024
Add new element to existing JSON array with jq - Stack Overflow
(windows JQ user here): I wonder if it is possible to write this new data to the same (input) file, instead of creating a temporary file which needs to be renamed afterwords.. 2017-08-04T01:20:54.697Z+00:00 ... @script'n'code - Using sponge is probably still the best option if you have it or can install it (it's part of moreutils). 2018-01-31T22:09:23.647Z+00:00 ... @peak how can I insert that object to the beginning of the array... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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 ...
🌐
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 ([])....
Find elsewhere
Top answer
1 of 2
4

You can accomplish this by wrapping $n in parenthesis to tell jq to evaluate the expression:

n="foo"; echo "{}" | jq --arg n "$n" '. += { ($n): $n }'

Or probably better suited for this task would be jo(1):

$ jo "$n"="$n"
{"foo":"foo"}

I'm not sure if the documentation is just wrong or if my ability to comprehend is not at a high enough level but it does seem to say that your example should work:

Key expressions other than constant literals, identifiers, or variable references, need to be parenthesized, e.g., {("a"+"b"):59}.

And one might assume that is referring to a jq native variable rather than one injected by the shell as they are slightly different, but alas both need to be parenthesized:

$ echo '{}' | jq 'def myvar: "foo"; {myvar: myvar}'
{
  "myvar": "foo"
}
$ echo '{}' | jq 'def myvar: "foo"; {(myvar): myvar}'
{
  "foo": "foo"
}
2 of 2
4

You can use:

$ n=foo
$ jq -cn --arg n "$n" '{$n:$n}'
{"foo":"foo"}

That is use the variable $n as the key, not the "$n" string. jq -n is like echo null | jq.

$ jq -cn --arg n "$n" '.[$n]=$n'
{"foo":"foo"}

Not using the {...} object constructor but assigning a value for a given key.

$ jq -cn --arg n "$n" '{"key\($n)":$n}'
{"keyfoo":"foo"}

Showing how to dereference a jq variable inside a string literal (in \(expr), expr can be any jq expression, not just a variable).

$ jq -cn --arg n "$n" '{("key"+$n):$n}'
{"keyfoo":"foo"}

In an object constructor, when keys are to be the result of a jq expression, they must be inside (...).

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 |= [ _ ] + .
🌐
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
🌐
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
🌐
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 ·
🌐
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
If you're dealing with just two properties from an object, just select the objects to put into an array, then put into an array. [ .element1, .element2 # select properties element1 then element2 ] # wrapped in [] creates the array
🌐
GitHub
gist.github.com › joar › 776b7d176196592ed5d8
Add a field to an object with JQ · GitHub
$ echo '{"hello": "world"}' | jq --arg foo bar '. + {foo: ("not" + $foo)}' { "hello": "world", "foo": "notbar" } ... I have json which is an object containing a property that is an array, and I want to create another property with the same value as an existing property, without changing anything else.
🌐
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} ]'