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
{
"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 |=.