Home > OS >  Unwanted backslashes in json response
Unwanted backslashes in json response

Time:06-11

I've wasted about 4 hours on different combinations of json.dumps, json.loads, etc... trying to figure this out to no avail. It appears my sting is being double serialized, but I have no idea how or why. Need some help. I get the following output from my API call:

{"error": "message\": \"Invalid parameter options - \"to\" must be later than \"from\"."}

I do NOT want these backslashes in the response.

Code snippet below:

err_msg = 'message": "Invalid parameter options - "to" must be later than "from".'
        
if err_msg != '':
    #Some error has occurred.  Send it back in the response.
    result = {}
    result['error'] = err_msg

    responseObject = {}
    responseObject['statusCode'] = 400
    responseObject['headers'] = {}
    responseObject['headers']['Content-Type'] = 'application/json'
    responseObject['body'] = json.dumps(result)
    return responseObject

CodePudding user response:

You have unwanted backslashes because the double-quotes need to be escaped (In JSON).

You could change err_msg to something like:

err_msg = "message": "Invalid parameter options - 'to' must be later than 'from'."

(Sorry if I got something wrong, I don't really use the JSON library in Python much and I don't really use JSON)

CodePudding user response:

JSON uses double quote " in its protocol so it has to escape double quotes found inside strings to avoid confusion. The serialized JSON has escapes... but who cares? That's just computer to computer stuff. Deserialize and it will all look correct again.

The original string

>>> import json
>>> err_msg = 'message": "Invalid parameter options - "to" must be later than "from".'
>>> print(err_msg)
message": "Invalid parameter options - "to" must be later than "from".

serialized

>>> serialized = json.dumps(err_msg)
>>> print(serialized)
"message\": \"Invalid parameter options - \"to\" must be later than \"from\"."

deserialized

>>> deserialized = json.loads(serialized)
>>> print(deserialized)
message": "Invalid parameter options - "to" must be later than "from".

and its the same stuff

>>> deserialized == err_msg
True
  • Related