1

How do I update a single value in a json document using jq? Doesn't have the answer for this question.

  1. Read json file.
  2. Update the value.
  3. Replace the file.

Expecting one inline command using jq

Assume I have following json file.

{
  "name": "app",
  "value": "one",
  ... 
}

I want to update the value field to "two". So resulting json file should look like

{
  "name": "app",
  "value": "two",
  ... 
}

What is the simplest bash command and windows bat command for this.

sith
  • 3,034
  • 6
  • 26
  • 46

1 Answers1

3

Here is a demonstration of a solution that uses sponge

bash-3.2$ cat data.json
{
  "name": "app",
  "value": "one"
}

bash-3.2$ jq -M '.value="two"' < data.json | sponge data.json 

bash-3.2$ cat data.json 
{
  "name": "app",
  "value": "two"
}
jq170727
  • 11,184
  • 3
  • 39
  • 52
  • sponge: command not found. overwriting file is file. – sith Sep 12 '17 at 06:45
  • sponge can be found in [moreutils](http://joeyh.name/code/moreutils/). There is a windows version [here](https://github.com/zetamatta/sponge) – jq170727 Sep 12 '17 at 06:48
  • can you give me the command with replacing the file using ">" – sith Sep 12 '17 at 06:50
  • There are some examples in [these discussions](https://stackoverflow.com/search?q=+sponge+moreutils), e.g. [Bash: Is it ok to use same input file as output of a piped command?](https://stackoverflow.com/questions/3055005/bash-is-it-ok-to-use-same-input-file-as-output-of-a-piped-command/3055080#3055080) but I would recommend using sponge. – jq170727 Sep 12 '17 at 06:57