I'm trying to run a script which issues rest commands via curl to an endpoint. If I put spaces in fields via something like insomnia, it works, but when I try from an input file, it's failing with a json error.
while IFS=, read mname oname <------ my input file is: Test Name,New Name
do
#echo $mname
....
....
curl --request POST \
--url http://192.168.0.1:1111/Service2/configuration/v1.0/Endpoint/ \
--header 'authorization: Bearer '$token \
--header 'content-type: application/json' \
--silent \
--data '{
-- "mName": "Test Name", <------with this line it works
"mName": '\"$mname\"', <-------with this line it fails
The output is
Test Name New Name
{"message":"JSON parse error","statusCode":400}
I've discovered a handy little tool called jq which can be used to build, display and manipulate JSON. If you are on Linux you can probably install it from the repository. Then you could change your curl invocation from
tried both ways. removed all my white spaces and tried a variable. Here is a better code stub which shows the full data element.
...
json_data=$(printf '{"mName":"%s","oName":"%s","lCode":"%s","schema":[{"name": "Fred","RequestId":"1234","Name":"Test","BO":"999999","aId":"%s","keyId":"p1","eId":"Test.ts"}],"cCode":"%s","cCode2":"GB","Url":{"protocol":"http","host":"test.co.uk","port": 1653,"endpoints":[{"name": "requestorEndpoint","value": "mEP"}]}}' "$mName" "$oName" "$lCode" "$aId" "$cCode")
curl --request POST \
--url http://192.168.1.12:12345/pSvc/config/ps2Req/ \
--header 'authorization: Bearer '$token \ <--------- $token comes from further up in the code.
--header 'content-type: application/json' \
--silent \
--data '${json_data}' <-------- note I had to use single quotes
done < $infile
The goal is to have "quotes" around the text with spaces.
But you must quote these "quotes" to hide them for the shell. Place them inside 'ticks' is one method.
And you must have $variables in "quotes" for the shell - these protective quotes are removed, when passed to the curl.
'{"text": "'"${message}"'"}'
And this is a concatenation of 'string' "string" 'string' where the shell passes stringstringstring to curl.