I have a JSON file, I'm trying to change a particular value in it using a script.
"foo-bar": "baz",
It is set as baz in this example, but in practice I don't know what this value is.
I want to change foo-bar
's value from within a larger script.
"foo-bar": "qux",
I tried
$var='qux'
jq --arg passvar ${var} '{"foo-bar":$passvar}' file.json
I get the correct output in terminal
{
"foo-bar": "qux"
}
But when I check the actual file contents using vim, I get
"foo-bar": "baz",
jq
doesn't want to save the new file.json? Or is that a preview of some sort?
What am I missing? Is there a better way than jq
to update/set values in a json file?
*edited to add a dash to the initial variable, it is now foo-bar instead of just foo.
CodePudding user response:
According to the documentation:
The output(s) of the filter are written to standard out
So, you need to redirect the output to whatever file you want.
jq --arg passvar ${var} '{"foo":$passvar}' file.json > newfile.json
CodePudding user response:
True answer is here https://stackoverflow.com/a/42718624/1286903
tmp=$(mktemp)
jq --arg p "$passvar" '."foo-bar" = $p' file.json > "$tmp" && mv "$tmp" file.json
You need to make use of a temp file to do this. Also, be mindful of quotes when your vars have dashes.