35

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" 
    ...
}

4 Answers 4

44

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
Sign up to request clarification or add additional context in comments.

4 Comments

Why the two moves?
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.
jq -r '.name |= "adar"' package.json | sponge package.json "sponge" comes in the "moreutils" package which must be installed first.
How can I replace the value if the key name is with a dot? For example user.password?
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"})'

Comments

1

With the sde CLI utility, you can

sde name adar package.json

Comments

-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

1 Comment

Dude, he meant programmatically. Of course you could manually edit the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.