Python中JSON数据解析问题:json.loads()函数报错求助
Python JSON解析报错问题
我正在开发一个Python项目,需要解析JSON数据,但使用json.loads()函数时遇到报错。从API获取JSON字符串后,调用该函数解析时出现如下错误:
Traceback (most recent call last): File "script.py", line 10, in <module> parsed_data = json.loads(json_string) File "/path/to/python/lib/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/path/to/python/lib/json/decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/path/to/python/lib/json/decoder.py", line 380, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
我尝试解析的JSON数据片段如下:
{ 'key': 'value' , 'another_key': 123 }gt
我怀疑问题与JSON字符串中的单引号有关,但尝试使用json.loads(json_string.replace('\'', '"'))将单引号替换为双引号后,错误仍然存在,寻求解决方法。
解决方法
- 清理无效后缀:你的JSON字符串末尾有多余的
gt字符,这是解析失败的核心原因之一。先移除这部分无效内容:# 精准移除末尾的gt json_string = json_string[:-2] # 或者更通用的正则匹配方式 import re match = re.search(r'\}\s*$', json_string) if match: json_string = json_string[:match.end()] - 替换单引号为双引号:标准JSON要求属性名和字符串值必须用双引号,完成清理后再做引号替换:
json_clean = json_string.replace("'", '"') parsed_data = json.loads(json_clean) - 用ast.literal_eval替代解析:如果API返回的是类似Python字典的格式(单引号),可以直接用
ast.literal_eval()解析,无需替换引号,还能兼容部分非标准格式:import ast # 先清理末尾无效字符 json_clean = json_string[:-2] parsed_data = ast.literal_eval(json_clean) - 验证API返回内容:打印完整的
json_string确认是否存在其他格式问题,比如多余换行、特殊字符。如果这类问题频繁出现,建议反馈给API提供者修复输出格式,从源头解决问题。
内容的提问来源于stack exchange,提问作者Rakhi Verma
相关产品推荐
相关产品推荐

