I have file like this(exact format):
{ "test": "10" }
{ "games": "30" }
{ "REPOSITORY": "5"}
I want to update the value of key. For example games to 66. So the new file would be:
{ "test": "10" }
{ "games": "66" }
{ "REPOSITORY":"5"}
I used jq with combination of a temporary file
tmp=$(mktemp);
jq '.games = "66"' pair.json > "$tmp" && mv "$tmp" change.json
but got this kind of output.
{
"test": "10",
"games": "66"
}
{
"games": "66"
}
{
"REPOSITORY": "5",
"games": "66"
}
where games is written all 3 whereas I just want it be updated only at its position. Furthermore i want the value to be updated using bash variable but that I can try to figure out using --arg after I resolve this issue. Pls assist here.
CodePudding user response:
Your input is a stream of objects. As such your filter expression, .games = "66"
asserts that the record games
is present in each of the object present in the stream.
To update the specific object alone, select it first and assign the required value or update it.
jq --compact-output 'select(has("games")).games = "66"'
CodePudding user response:
Only select
those objects with .games
key before updating:
select(.games).games |= "66"
With 'Compact output':
jq --compact-output 'select(.games).games |= "66"' pair.json