0

I want to add a couple fields to a json file in a shell script. The values for both files come in a parameter and there doesn't seem to be a way to make sed or jq work with such values. I've traid with simple and double quotes everywhere but can't make it work.

sh myscript.sh 'value' 'second value'

firstValue=$1
secondValue=$2

jq '.firstField="'$firstValue'" | .secondField="'$secondValue'"' $jsonFileAddress
sed -i '$s/}/,"firstField":"'$firstValue'","secondField":"'$secondValue'"}/' $jsonFileAddress
Rajo
  • 71
  • 10
  • 2
    Please follow the [mcve] guidelines as much as possible. In particular, some details about the contents of the file at $jsonFileAddress would be helpful. – peak Dec 28 '21 at 00:09
  • When you do `'something'$var'and more'`, the expansion of `$var` is unquoted. You need to use `'something'"$var"'and more'` instead. Also, for jq, you should pass values from the shell using `--arg`, and not with interpolation. – Benjamin W. Dec 28 '21 at 03:56

1 Answers1

0

Bengamin W. comment put me on track with the use of arguments. I finally managed to append a couple of new fields to an existing json file like this:

echo $(jq --arg a "$firstValue" --arg b "$secondValue" '.firstField=$a | .secondField=$b' $jsonFileAddress) > $jsonFileAddress

Rajo
  • 71
  • 10