1

Background

Original json (test.json): {"rpc-password": "password"}

Expected changed json: {"rpc-password": "somepassword"}

replace_json_str is a function used to replace password with somepassword using sed.

replace_json_str() {
    x=$1
    sed -i -e 's/\({ "'"$2"'":\)"[^"]*" }/\1"'"$3"'" }/g' $x
}

Unit test: replace_json_str test.json rpc-password somepassword

Issue

After running the above test, I get a file named test.json-e and the contents of the file is the same as before the test was ran, why?

Nicholas Adamou
  • 711
  • 10
  • 23

2 Answers2

3

there is a handy command line json tool called jq

cat input.json
{"rpc-password": "password"}

cat update_json.sh

givenkey=$1
givenvalue=$2

inputfile=input.json
outfile=output.json

cat $inputfile  | jq .   #  show input json

jq --arg key1 "$givenkey" --arg val1 "$givenvalue"  '.[$key1] = $val1' "$inputfile" > "$outfile"

cat "$outfile" | jq .     #  render output json

keep in mind jq can handle multiple such key value updates ... execute it

update_json.sh  rpc-password somepassword
{
  "rpc-password": "password"
}
{
  "rpc-password": "somepassword"
}
Scott Stensland
  • 26,870
  • 12
  • 93
  • 104
1

Depends on which sed you're using.

The command you ran will work as expected with GNU sed.

But BSD sed does not allow for an empty argument to -i, and if you ran the same command, it will use the next argument, -e, as the backup file.

Also, the positioning of the spaces in your pattern don't match your example JSON.

ephemient
  • 198,619
  • 38
  • 280
  • 391