JSON data containing `\\\` in between [closed]

2019-08-14 19:43发布

I have a python listening server written as a Flask application.This server is listening to POST messages from a remote source.The remote source is posting JSON documents. A sample JSON document that I recieved is shown below.

{

    "Timestamp": "1432241553492",
    "data": "[{\"EventName\":\"Time\",\"Category\":\"Experience\",\"Severity\":\"warn\",\"Subject\":\"Time\",\"Message\":\"details:{\\\"Message\\\":\\\"https://xxxx.xxxxx.com/ (1882 ms : ATime: 5 ms, BTime: 1108 ms, CTime: 769 ms), \\\",\\\"Time\\\":\\\"Fri May 22 2015 08:52:33 GMT+1200 (NZST)\\\",\\\"MobileDevice\\\":\\\"Not Mobile\\\",\\\"User\\\":\\\"user.name\\\",\\\"CPUs\\\":8,\\\"Language\\\":\\\"en-GB\\\",\\\"isEvent\\\":\\\"true\\\",\"Stamp\":\"1432241553492\"}]",
    "msgType": "0",
    "tid": "1"
}

This file is supposed to be a proper JSON file.But I get \\\ in between the fields as shown above.I am wondering if something is wrong with the setting of Http OPTIONS in my listening server or the data type perhaps. It would be great if someone can help me to figure it out.

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-14 20:05

At first glance you appear to have a botched JSON file; there is a stray ," sequence in there that breaks the format.

If you removed entries, it may well be that you broke the format; if your actual string validates on http://jsonlint.com then you did just that.

Backslashes are valid escape sequences in JSON. You have data that contains other JSON strings, which in turn contain more encoded JSON data. You can recursively decode those:

>>> import json
>>> print json.dumps({'object': 'deeply nested'})
{"object": "deeply nested"}
>>> print json.dumps({'wrapper': json.dumps({'object': 'deeply nested'})})
{"wrapper": "{\"object\": \"deeply nested\"}"}
>>> print json.dumps({'outermost': json.dumps({'wrapper': json.dumps({'object': 'deeply nested'})})})
{"outermost": "{\"wrapper\": \"{\\\"object\\\": \\\"deeply nested\\\"}\"}"}

Note that as the level of wrapping increases, so do the backslashes. First the embedded " quotes get escaped to \", followed by escaping of the backslash and the quote to \\\", etc.

You probably want to fix the code that produces this nesting. Don't encode individual objects, then store them in something else.

Don't do this:

event['details'] = json.dumps(event_detail_data)
message['data'] = json.dumps(event)
json_to_send = json.dumps(message)

That'd create a nested structure. Only encode the final object:

event['details'] = event_detail_data
message['data'] = event
json_to_send = json.dumps(message)
查看更多
登录 后发表回答