带有转义字符python3的json.loads()

时间:2019-12-13 16:15:23

标签: python json python-3.x jsonparser

我有一个来自运动学流的数据,并且有转义字符。当我尝试使用json.loads在python3中将数据转换为json格式时,它失败json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 22 (char 21)

下面是示例事件,

event='{"logEvents":[{"message":"{\"objectType\":\"HANDLER_OBJECT\",\"event\":{\"source\":\"Test\",\"action\":\"PLAY\",\"type\":\"SH\",\"timestamp\":1576223901848,\"key\":\"A|12|B|12|C|123|R|1|SH\",\"value\":\"{\\\"type\\\":\\\"THIS_IS_TEST\\\",\\\"objectId\\\":\\\"123ae43fd46fg\\\",\\\"containerId\\\":\\\"122122321212343212\\\",\\\"testId\\\":\\\"0\\\",\\\"testContainerId\\\":\\\"122122321212343212\\\",\\\"version\\\":4,\\\"reattemptVersion\\\":1,\\\"pId\\\":\\\"122122321212343212|123ae43fd46fg\\\",\\\"active\\\":true,\\\"sOn\\\":1576222508,\\\"cOn\\\":0,\\\"time\\\":1576226109,\\\"hIds\\\":[],\\\"mScore\\\":4000,\\\"cy\\\":null,\\\"ceOn\\\":null,\\\"rr\\\":[],\\\"cS\\\":null}\"}}"}]}'

我尝试过的代码

json.loads(event)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 1 column 29 (char 28)

我知道将\转换为\\将解决此问题,但是有时还会出现特殊字符,因此不能仅使用replace处理。

我也检查了类似的SO问题和解决方案,但没有一个起作用。我已经尝试过json.loads(event.encode('unicode_escape'))json.loads(r'{}'.format(event)),但是都没有用。有人可以在python3中提供解决方案或更好的json解析模块/库吗?

1 个答案:

答案 0 :(得分:0)

我不确定数据来自哪里,但是!但是我们来了!

import json

event = r'{"logEvents":[{"message":"{\"objectType\":\"HANDLER_OBJECT\",\"event\":{\"source\":\"Test\",\"action\":\"PLAY\",\"type\":\"SH\",\"timestamp\":1576223901848,\"key\":\"A|12|B|12|C|123|R|1|SH\",\"value\":\"{\\\"type\\\":\\\"THIS_IS_TEST\\\",\\\"objectId\\\":\\\"123ae43fd46fg\\\",\\\"containerId\\\":\\\"122122321212343212\\\",\\\"testId\\\":\\\"0\\\",\\\"testContainerId\\\":\\\"122122321212343212\\\",\\\"version\\\":4,\\\"reattemptVersion\\\":1,\\\"pId\\\":\\\"122122321212343212|123ae43fd46fg\\\",\\\"active\\\":true,\\\"sOn\\\":1576222508,\\\"cOn\\\":0,\\\"time\\\":1576226109,\\\"hIds\\\":[],\\\"mScore\\\":4000,\\\"cy\\\":null,\\\"ceOn\\\":null,\\\"rr\\\":[],\\\"cS\\\":null}\"}}"}]}'


def to_python(event):
    event = eval(event)

    for e in event['logEvents']:
        e['message'] = json.loads(e['message'])
        e['message']['event']['value'] = json.loads(e['message']['event']['value'])

    return event


from pprint import pprint

pprint(to_python(event))

输出

{'logEvents': [{'message': {'event': {'action': 'PLAY',
                                      'key': 'A|12|B|12|C|123|R|1|SH',
                                      'source': 'Test',
                                      'timestamp': 1576223901848,
                                      'type': 'SH',
                                      'value': {'active': True,
                                                'cOn': 0,
                                                'cS': None,
                                                'ceOn': None,
                                                'containerId': '122122321212343212',
                                                'cy': None,
                                                'hIds': [],
                                                'mScore': 4000,
                                                'objectId': '123ae43fd46fg',
                                                'pId': '122122321212343212|123ae43fd46fg',
                                                'reattemptVersion': 1,
                                                'rr': [],
                                                'sOn': 1576222508,
                                                'testContainerId': '122122321212343212',
                                                'testId': '0',
                                                'time': 1576226109,
                                                'type': 'THIS_IS_TEST',
                                                'version': 4}},
                            'objectType': 'HANDLER_OBJECT'}}]}