1

I have the following:

COMMENT="A random comment"  
TEXT_JSON='{"person" : "Jim","comment" : "$COMMENT"}'    
echo "$TEXT_JSON" | jq .  

This prints

{  
  "person": "Jim",  
  "comment": "$COMMENT"  
} 

which is not what I want. How can I interpolate the string here?

1
  • 1
    In the particular case of jq, you should probably be using its own --arg argument-passing facility, I think – steeldriver Jun 5 '18 at 11:56
2

You cannot interpolate inside single quotes.

You can put the string in double quotes, then escape the literal double quotes:

COMMENT="A random comment"
TEXT_JSON="{\"person\" : \"Jim\",\"comment\" : \"$COMMENT\"}"
echo $TEXT_JSON | jq .
{  
  "person": "Jim",  
  "comment": "A random comment"  
} 

Or alternatively you can keep the single quotes so you don't have to escape anything, but end the single quotes before the variable, then use double quotes for the variable, then single quotes for the last part of the string:

TEXT_JSON='{"person" : "Jim","comment" : "'"$COMMENT"'"}'
1
  • This would fail if $COMMENT contained a newline, tab, double quote or any other character that needs to be JSON encoded. – Kusalananda Jul 11 at 17:55
0

Shell variable are never expanded in single-quoted strings in the shell.

To create a JSON document with data from a shell variable, use a JSON aware tool like jq or jo. This ensures that the data is adequately encoded fro inclusion in the document. Expanding a shell variable in a JSON document is not what you want to be doing.

Using jq:

comment='Some comment from "Random User"'
jq -n --arg comment "$comment" '{ "person": "Jim", "comment": $comment }'    

Using jo:

comment='Some comment from "Random User"'
jo person=Jim comment="$comment"

Both of these creates the equivalent JSON that may be represented as

{
  "person": "Jim",
  "comment": "Some comment from \"Random User\""
}

Note how the double quotes were automatically handled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.