Home > database >  How to preserve line breaks when sending JSON using cURL?
How to preserve line breaks when sending JSON using cURL?

Time:05-10

The following almost works, but line breaks in message property are not preserved.

output="$(ls -la /home/john | gpg --armor --encrypt --recipient [email protected])"
curl \
  --request POST \
  --url https://api.example.net/sendmail \
  --header 'Content-Type: application/json' \
  --data @- << EOF
{
  "subject": "Test",
  "message": "$output"
}
EOF

Thanks for helping out!

CodePudding user response:

You need to replace all the newlines with \n in the JSON string:

message=${message//$'\n'/\\n}

However, I recommend using a utility like jq rather than ad hoc code like this. You also need to escape double quotes and backslashes in the string, and convert non-ASCII characters to \u#### escape sequences.

  • Related