Reputation: 626
I looked at the following questions because I was having trouble with string interpolating my JSON, but still having trouble.
Here is code: (Sorry for the horizontal scrolling)
JSON_DATA=\''{"notification": {"title": "'"$TITLE"'", "body": "'"$BODY"'", "sound": "'"${SOUND}"'"}, "to": "'"$DEVICE_ID"'"}'\'
Which returns me a well structured JSON (in a string).
'{"notification": {"title": "random test", "body": "here is big body", "sound": "default"}, "to": "ejKgihBpSt4:APA91bGBl"}'
Then when I fire my CURL:
curl -H "Content-type: application/json" -H "Authorization:key=$FIREBASE_SERVER_KEY" -X POST -d "$JSON_DATA" https://fcm.googleapis.com/fcm/send
I get the following error: JSON_PARSING_ERROR: Unexpected character (') at position 0.
If I put the ${JSON_DATA} outside of the double quotes, then I get the following error:
curl: (3) [globbing] unmatched brace in column 1
curl: (6) Could not resolve host: "random
curl: (6) Could not resolve host: test",
curl: (6) Could not resolve host: "body"
curl: (6) Could not resolve host: "here
curl: (6) Could not resolve host: is
curl: (6) Could not resolve host: big
curl: (6) Could not resolve host: body",
curl: (6) Could not resolve host: "sound"
curl: (3) [globbing] unmatched close brace/bracket in column 10
curl: (6) Could not resolve host: "to"
curl: (3) [globbing] unmatched close brace/bracket in column 24
JSON_PARSING_ERROR: Unexpected character (') at position 0.
Upvotes: 1
Views: 340
Reputation: 780871
Get rid of \'
around the string. It's not needed and is invalid in JSON.
JSON_DATA='{"notification": {"title": "'"$TITLE"'", "body": "'"$BODY"'", "sound": "'"${SOUND}"'"}, "to": "'"$DEVICE_ID"'"}'
Note that this will produce incorrect results if any of the variables contains double quotes, newlines, or other special characters that have to be escaped in JSON. It would be best if you installed the jq
utility and used it to create the JSON for you. See jq & bash: make JSON array from variable for examples.
Upvotes: 3