I have to send a POST request to some service with JSON payload, and it includes some user input. That input variable needs to be JSON-encoded to prevent injection attacks.

Code example that sends requests and parses response JSON to RESP variable:

RESP=`curl --connect-timeout "10" -s -H "Content-Type: application/json" \
        -X POST -d '{ "Attribute": '"'$USERINPUT'" }',\
        $ENDPOINT | $JQ -r '.key'`

How to sanitize, or JSON encode, $USERINPUT before creating JSON payload?

  • 2
    Use a real programming language with a proper JSON library, e.g. Python, Perl, Ruby, whatever.
    – choroba
    Commented Aug 18, 2016 at 15:59

2 Answers 2


Using the jo utility, the sanitized JSON document could be constructed using

data=$( jo Attribute="$USERINPUT" )

You would then use -d "$data" with curl to pass this to the endpoint.

Old (but still valid) answer using jq instead of jo:

Using jq:

USERINPUT=$'a e""R<*&\04\n\thello!\''

This string has a couple of double quotes, an EOT character, a newline, a tab and a single quote, along with some ordinary text.

data="$( jq -nc --arg Attribute "$USERINPUT" '$ARGS.named' )"

This builds a JSON object containing the user data as the value for the lone Attribute field.

From this, we get


as the value in $data.

This can now be used in your call to curl:

RESP="$( curl --connect-timeout "10" -s \
           -H "Content-Type: application/json" \
           -X POST -d "$data" \
           "$ENDPOINT" | jq -r '.key' )"

You can use the Python module json.tool from the command line to parse JSON:

export USERINPUT="[1,2,3]"
echo $USERINPUT| python -mjson.tool

You must log in to answer this question.

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