skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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:

    code = "date1.setValue('2023-01-01 00:00:00')"  # Removed unnecessary double quotes and backslashes
    
    payload = {
        "id": "1",
        "inputs": [
            {
                "datatype": "BYTES",
                "data": [code],  # Just use the variable directly
            }
        ],
        # ...
    }
    
    Login or Signup to reply.
  3. create a json_payload to convert a python object into a JSON string using json.dumps():

    import json
    
    json_payload = json.dumps(payload)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search