jsonjq

jq argjson does not work with string from variable


I am trying to create a json with jq

f=1
jq -n --argjson a ${f} '{"test":$a}'

or

f="1"
jq -n --argjson a ${f} '{"test":$a}'

or

jq -n --argjson a "teststring" '{"test":$a}'

work fine

but

f="teststring"
jq -n --argjson a ${f} '{"test":$a}'

yields jq: invalid JSON text passed to --argjson

What am I doing wrong?

Cheers Gordon


Solution

  • Your shell is interpreting the double quotes and passing bare strings to jq.

    The correct way to define your input is to add an extra level of quoting to make the double quotes part of the value:

    f='"teststring"'
    jq -n --argjson a "${f}" '{"test":$a}'
    

    As shown, you also need to quotes around the use of $f in case it contains whitespace.