【发布时间】:2019-12-13 16:15:23
【问题描述】:
我有一个来自 kinesis 流的数据,它有转义字符。当我尝试使用 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)
我知道将\ 转换为\\ 可以解决这个问题,但有时也会出现特殊字符,因此不能仅使用替换来处理。
我也检查了类似的 SO 问题和解决方案,但没有一个有效。我尝试过json.loads(event.encode('unicode_escape')) 和json.loads(r'{}'.format(event)),但都没有奏效。任何人都可以在 python3 中提供解决方案或更好的 json 解析模块/库吗?
【问题讨论】:
-
请显示
print(events)的输出 -
什么是
event?请注意,您的 JSON 中的以下键:"{\"objectType\":\"HANDLER_OBJECT\",\"event\"...看起来有人将有效的 JSON 字符串序列化为 JSON 对象的一部分……您为什么要这样做? -
@AlexandrShurigin 事件是我之前在问题中显示的 json 字符串,我现在已经更新了问题。
-
@juanpa.arrivillaga 这是我从 kinesis 获得的事件字符串的结构,我正在尝试将其转换回 json。
-
数据从哪里来?我确定它不是 JSON。这是某种混合。但是您为
event=添加的数据在转义时不正确
标签: python json python-3.x jsonparser