33

Is it possible to change the value of a key in a JSON file from command line?

e.g., in package.json:

Change

{
    ...
    ...
    "something": "something",
    "name": "idan" 
    ...
}

To

{
    ...
    ...
    "something": "something",
    "name": "adar" 
    ...
}
Idan Adar
  • 44,156
  • 13
  • 50
  • 89

4 Answers4

43

One way to achieve it is by using the "json" npm package, e.g.:

json -I -f package.json -e "this.name='adar'"

Another way is by using the jq CLI, e.g.:

mv package.json temp.json
jq -r '.name |= "adar"' temp.json > package.json
rm temp.json
Marcel Falliere
  • 1,884
  • 21
  • 39
Idan Adar
  • 44,156
  • 13
  • 50
  • 89
  • Why the two moves? – Charlie Dec 20 '20 at 22:41
  • The move and the redirect are a good idea because the alternative is to redirect into the original file, and if there's an error parsing the file with jq, you will loose the original file. – Mig82 Mar 05 '21 at 11:03
  • 2
    jq -r '.name |= "adar"' package.json | sponge package.json "sponge" comes in the "moreutils" package which must be installed first. – denik1981 Jan 09 '22 at 13:41
  • How can I replace the value if the key name is with a dot? For example `user.password`? – andrew Apr 13 '22 at 11:00
2

With :

$ xidel -s --in-place package.json -e '($json).name:="adar"'
$ xidel -s --in-place package.json -e 'map:put($json,"name","adar")'
$ xidel -s --in-place package.json -e 'map:merge(($json,{"name":"adar"}),{"duplicates":"use-last"})'
Reino
  • 3,203
  • 1
  • 13
  • 21
1

With the sde CLI utility, you can

sde name adar package.json
Danila Vershinin
  • 8,725
  • 2
  • 29
  • 35
-8

The anoter way is to open the file itself in terminal :

pico filename.json

edit it then save then exit.

check if correct changes were made:

cat filename.json