Encode raw text to use as JSON in a bash script


I recently needed to send random text as JSON in bash script. The raw text could include double quotes, dollar signs and/or newlines, so it needed to be encoded/escaped/sanitized.

Note: I am not certain if there are any security holes in this: in my case this wasn’t a concern.

ENCODED="$( jq --null-input --compact-output --arg str "$RAW" '$str' )"

You need to get the wacky value in the $RAW variable on your own!

Full example:

RAW=$'a e""R<*&\04\n\thello!\''
ENCODED="$( jq --null-input --compact-output --arg str "$RAW" '$str' )"
echo "{\"encoded\": ${ENCODED}}" | jq .

source

Tags:  json  jq  curl

Share: