0

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.

dfelix
  • 71
  • 1
  • 6
  • see: [Jq to replace text directly on file (like sed -i)](https://stackoverflow.com/questions/36565295/jq-to-replace-text-directly-on-file-like-sed-i) – pilchard Nov 02 '21 at 22:35
  • Your attempt *ignores* `file.json` and outputs the object created by your filter. – chepner Nov 03 '21 at 15:15
  • `jq` can only read from a file and write to standard output; it has no facilities for writing to any other file. – chepner Nov 03 '21 at 15:16

2 Answers2

1

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
Octavio Galindo
  • 330
  • 2
  • 9
  • Thanks for the reply. Indeed, and if you want to pass it to the same file, `file.json`, you need to pass it to a temp file `tmp.json` then back to `file.json`. – dfelix Nov 12 '21 at 23:25
0

True answer is here https://stackoverflow.com/a/42718624/1286903

tmp=$(mktemp)
jq --arg p "$p" '."foo-bar" = $p' file.json > "$tmp" && mv "$tmp" file.json

'."foo-bar" is the key you want to edit.

You need to make use of a temp file to do this. Also, be mindful of quotes when your vars have dashes.

dfelix
  • 71
  • 1
  • 6