gpt4 book ai didi

python - Python中的JSON字符串解析错误

转载 作者:太空宇宙 更新时间:2023-11-03 14:07:15 25 4
gpt4 key购买 nike

我正在向 API 发送请求,它返回此 JSON 响应

'{"Reply":{"Header":{"Method":"mGSSCBetHistory","ErrorCode": "0","MerchantID":"BETSTARtest","MessageID": "H140201152657m6k3f"},"Param":{"TotalRecord":"1","BetDatas":"[{"Column1":""}]","ErrorDesc": ""}}}'

当我尝试将其转换为字典时,无论是 ast.literal_eval 还是 json.loads,它都会返回此错误:

Traceback (most recent call last):
File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/lib/python2.7/site-packages/celery/app/trace.py", line 367, in trace_task
R = retval = fun(*args, **kwargs)
File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/lib/python2.7/site-packages/celery/app/trace.py", line 622, in __protected_call__
return self.run(*args, **kwargs)
File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/provider/KENO/tasks.py", line 127, in run
['Reply', 'Param', 'BetDatas'], 'post')
File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/core/classes.py", line 217, in check_records
self.result = response.json()
File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/lib/python2.7/site-packages/requests/models.py", line 826, in json
return complexjson.loads(self.text, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, 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 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting ',' delimiter: line 1 column 169 (char 168)

这是因为 BetDatas 的值在双引号内有一个双引号。对此有简单的解决方法吗?因为我能想到的唯一合适的解决方案是告诉第三方我一直在发送更改他们的 JSON 响应的请求。

最佳答案

使用正则表达式匹配违规值并使用 re.sub 转义匹配。

import re
import json

data = '{"Reply":{"Header":{"Method":"mGSSCBetHistory","ErrorCode": "0","MerchantID":"BETSTARtest","MessageID": "H140201152657m6k3f"},"Param":{"TotalRecord":"1","BetDatas":"[{"Column1":""}]","ErrorDesc": ""}}}'

def escape(match_obj):
print(match_obj.group(1))
return match_obj.group(1).replace('"','\"')
REGEX = '(?<="BetDatas":")(\S+)(?=",)'

data = re.sub(REGEX, escape, data)
print(data)

关于python - Python中的JSON字符串解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42529384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com