3

To add a property to a JSON text I manage to use

result=$(jq -c '.docs[0] + { "value": "someValue" }'<<<"$fileContent")

But if I want to replace "someValue" by a variable:

result=$(jq -c '.docs[0] + { "value": ($value) }'<<<"$fileContent")

This gives me

jq: error: value/0 is not defined at <top-level>, line 1:
.docs[0] + { "value": ($value) }
jq: 1 compile error

I also tried without braces $value and inside brackets [$value] without success.

1 Answer 1

13

Your jq expression is within single quotes. This stops $value from being expanded by the shell.

Instead, use jq with --arg to give a jq variable the JSON encoded value of the shell variable:

result=$(jq --arg value "$value" -c '.docs[0] + { "value": $value }' <<<"$fileContent")
2
  • Late to the game, but, how would one surround with double quotes the content of value? Using \" doesn't seem to work for me.
    – TechFanDan
    May 23, 2019 at 12:10
  • 1
    @TekiusFanatikus jq should add the quotes if they are needed. If you have value that is already a JSON encoded thing, use --jsonarg in place of --arg.
    – Kusalananda
    May 23, 2019 at 12:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .