Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update value in json object with key as argument (using `jq`)

Using jq I want to update a value in a json object.
The key of the value to be updated is passed as an argument.

Input

{
  "a": 1,
  "b": 2,
  "c": 3
}

Expected output with argument: key=b

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "a": 1,
  "b": 42,
  "c": 3
}

I tried to do:

jq --arg key b '.($key) |= . + 40'
jq --arg key b '".\($key)" |= . + 40'

Both attempts result in errors:

  • syntax error, unexpected '('
  • Invalid path expression with result ".b"

How can I solve this problem?

>Solution :

A key needs an . in front of it, then since it’s in a variable, use [].

jq --arg key b '.[$key] |= (. * 999)' input

Gives:

{
  "a": 1,
  "b": 1998,
  "c": 3
}

You can also replace |= . * with the *= operator:

jq --arg key b '.[$key] *= 999' input

Your first attempt didn’t work since you need [] instead off ()

The second one failed because wrapping it in a string literal will create a string .b, that’s not something you can update using |=.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading