Reputation: 104
I'm trying to add new field in a json file using jq:
jq -r --arg k "foo" --arg v "bar" '.newField += {$k:$v}' myfile
But it results in:
jq: error: syntax error, unexpected ':', expecting '}' (Unix shell quoting issues?) at <top-level>, line 1:
.newField += {$k:$v}
jq: error: May need parentheses around object key expression at <top-level>, line 1:
.newField += {$k:$v}
jq: 2 compile errors
When I remove key variable like below it works fine:
jq -r --arg k "foo" --arg v "bar" '.newField += {"static_key":$v}' myfile
Any idea how to use key name from jq arg?
Upvotes: 3
Views: 2633
Reputation: 9749
If this helps, using the following uses the arg var itself as json key, and the arg value as the json value:
$ jq -r --arg foo "bar" '.newField += {$foo}' myfile
....
"newField": {
"foo": "bar"
}
Upvotes: 2
Reputation: 131550
As the error message suggests, put parentheses around the key:
jq -r --arg k "foo" --arg v "bar" '.newField += {($k):$v}' myfile
jq requires keys given by expressions (i.e. not literal strings) to be parenthesized (noted in the manual).
Upvotes: 7