简体   繁体   English

json响应中不需要的反斜杠

[英]Unwanted backslashes in json response

I've wasted about 4 hours on different combinations of json.dumps, json.loads, etc... trying to figure this out to no avail.我在 json.dumps、json.loads 等的不同组合上浪费了大约 4 个小时……试图弄清楚这一点无济于事。 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:我从我的 API 调用中得到以下输出:

{"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

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. JSON 在其协议中使用双引号" ,因此它必须转义在字符串中发现的双引号以避免混淆。序列化的 JSON 有转义......但谁在乎呢?这只是计算机到计算机的东西。反序列化,它会再次看起来正确。

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

You have unwanted backslashes because the double-quotes need to be escaped (In JSON).您有不需要的反斜杠,因为需要转义双引号(在 JSON 中)。

You could change err_msg to something like:您可以将err_msg更改为:

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) (对不起,如果我弄错了,我并没有真正使用 Python 中的 JSON 库,我也没有真正使用 JSON)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM