Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set multiple values

Tags:

json

jq

Given this file

{
  "[global]": {
    "current": "",
    "hash": ""
  }
}

I would like this output:

{
  "[global]": {
    "current": "alpha",
    "hash": "bravo"
  }
}

I have this working command:

jq '."[global]".current="alpha" | ."[global]".hash="bravo"' example.json

However I would rather not have to repeat the ."[global]" part. I tried this command but it only returns part of the input:

$ jq '."[global]" | .current="alpha" | .hash="bravo"' example.json
{
  "current": "alpha",
  "hash": "bravo"
}
like image 817
Zombo Avatar asked Nov 20 '25 06:11

Zombo


1 Answers

The multiplication of objects recursively merges the two. You can merge the [global] object with an object with the new values. The string values on the RHS will be used in the result.

."[global]" *= { current: "alpha", hash: "bravo" }

Addtion would work here too, but multiplication is generally more useful, particularly with nested objects. Rather than replacing corresponding objects, they are also merged.

like image 139
Jeff Mercado Avatar answered Nov 22 '25 04:11

Jeff Mercado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!