'How to properly escape a JSON string for curl call in Jenkinsfile?

I am writing a Jenkinsfile and in the middle of a stage to call an API with a CURL command, I have something like:

sh '''

accept_hdr="Accept:*/*"
fetch_mode_hdr="Sec-Fetch-Mode: cors"
content_type_hdr="Content-Type: application/json"

currentMonth="03"
currentYear="2022"
studentID="12345"

data="[{"month":"${currentMonth}","year":"${currentYear}","id":"${studentID}"}]"

curl -k -v --include --header "$accept_hdr" --header "$content_type_hdr" --header "$fetch_mode_hdr" --data "$data" -X POST http://testurl:555/path/api/${studentID}

'''

When I check my logs, it's showing this:

curl -k -v --include --header 'Accept:*/*' --header 'Content-Type: application/json' --header 'Sec-Fetch-Mode: cors' --data '[{currentMonth:03,currentYear:2022,studentID: 12345}]' -X POST http://testurl:555/path/api/12345

It's giving me an error saying:

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('c' (code 114)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('c' (code 114)): was expecting double-quote to start field name

I see that this is because it is sending it as [{currentMonth:03,currentYear:2022,studentID: 12345}] instead of [{"currentMonth":"03","currentYear":"2022","studentID":"12345"}]

So I tried to escape the string online and used this instead: [{\"month\":\"${currentMonth}\",\"year\":\"${currentYear}\",\"id\":\"${studentID}\"}] but there was still the same error and it still was in the same format as before, without the double quotes.

Any idea how I can resolve this, I've been stuck for hours now trying to format it differently.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source