Post

jq - Update value in json with variable

I use jq for reading and filtering json on the command line.

Given the json below, I’d like to update the value of b to be 30. jq offers the update assignment, |=, for this.

1
2
3
4
5
6
{
  "a": {
    "b": 10
   },
  "c": 20
}

Try out the snippet at https://jqplay.org/s/t39OXPDrll-

Doing the same with that data saved to file, say myData.json and PowerShell and passing the new value as a jq variable would look like this:

1
2
3
4
5
6
{
  "a": {
    "b": 10
   },
  "c": 20
}

In the command line, run the following:

1
2
3
4
5
6
7
8
# retrieve b's value
C:\opt\jq-win64.exe '.a.b' myData.json

# set 30 to a powershell variable
$newValue = 30

# assign newValue to jq variable 'jqVarToUse' and pass it to the assigment operator
C:\opt\jq-win64.exe --arg jqVarToUse $newValue '.a.b |= $jqVarToUse' myData.json

jq gives the following output, and does not modify the original file.

1
2
3
4
5
6
{
  "a": {
    "b": "30"
   },
  "c": 20
}

To let jq make the change and directly modify the file, enclose the update in cat. In bash, it looks like this:

1
2
new_value=40
cat <<< "$(jq --arg jqVarToUse $newnew_valueValue '.a.b |= $jqVarToUse' myData.json)" > myData.json

What to watch out for: if there’s an error anywhere, the modified file (myData.json) will be empty.

Beware!

if there’s an error anywhere, the modified file (myData.json) will be empty.

This post is licensed under CC BY 4.0 by the author.