5

json processor jq for a package.json

{
  "someparent" : {
    "somechild" : "oldvalue"
  }
}

If I run the following command (to change oldvalue to somevalue):

jq '.someparent["somechild"] = "somevalue" "$aDirection/package.json"'

It is successfully changed. However, if I give a variable instead of someValue:

 aVar="anotherValue"
 jq '.someparent["somechild"] = "$aVar" "$aDirection/package.json"'

It is not working. What I already tried:

["aVar"] #interpreted as string
["$aVar"] #interpreted as string
"$aVar" # aVar is not defined
$avar #aVar is not defined
Asqan
  • 4,319
  • 11
  • 61
  • 100
  • I had seen that question but their answers don't fit this situation and also didn't work (e.g. `\"aVar\"`) – Asqan Dec 04 '17 at 17:25
  • 1
    @BenjaminW. the question can be seen like a duplicate for an expert user but it is absolutely not for beginners, qua type, qua solution and handled method. ps: as you said, json had just simplifying problem. – Asqan Dec 05 '17 at 10:09

2 Answers2

6

The single quotes around the jq filter are in the wrong place. In your attempt made it is also enclosing the actual JSON file input. The right syntax when applying filter over files is

jq '<filter>' json-file

In your case the right filter is just

.someparent["somechild"] = $aVar

and to use a shell variable in to the jq, you need to use the --arg field. Putting together both of the options. The first variable after --arg is used in the context of jq and the one following it is the actual shell variable.

aVar="anotherValue"
jq --arg aVar "$aVar" '.someparent["somechild"] = $aVar' "$aDirection/package.json"
#                                                    ^^^^ Remember the single quote 
#                                                    terminating here and not extended
Inian
  • 80,270
  • 14
  • 142
  • 161
2

Just to be clear: using the OP's approach can be made to work, e.g.

jq '.someparent["somechild"] = "'"$aVar"'"' "$aDirection/package.json"

but using --arg (for strings) and/or --argjson is far better. An additional option for environment variables is to use the jq function env.

peak
  • 105,803
  • 17
  • 152
  • 177