Unsure if title is an accurate way of phrasing question.
I have a JSON request and I’m passing in a variable "code". (It’s hardcoded here but it’s coming from another function)
code = ""date1.setValue('2023-01-01 00:00:00')""
data_string = f'{{"code": {code}}}'
payload = {
"id": "1",
"inputs": [
{
"datatype": "BYTES",
"data": [data_string],
}
],
...
}
The problem: in the request, the single quotes around the datetime is being escaped; but the backslash is showing up as part of request.
Is there a way to have that backslash not be there?
I did a normal print of the request:
{'id': '1', 'inputs': [{'datatype': 'BYTES', 'data': ['{{"code": "date1.setValue('2023-01-01 00:00:00')"']}]
The important part:
"code": "date1.setValue('2023-01-01 00:00:00')"
3
Answers
This is expected since
data
is a list containing a single string, the string is printed sorrounded by single quotes:'data': ['...']
, so the single quotes included inside the string must be escaped.It appears that the problem is due to how the JSON data is structured. Single quotes within double-quoted strings in JSON do not need to be escaped in Python. Here’s way to make the
payload
without the extra backslashes:create a
json_payload
to convert a python object into a JSON string usingjson.dumps()
: