JSONDecodeError求助:含嵌套引号的JSON字符串转字典失败
解决方案
你的问题出在两个核心点:
- Python字符串定义的语法冲突:外层用单引号包裹JSON字符串时,
description字段里的It's单引号会提前闭合外层的单引号,导致Python解析这个字符串时就已经截断了内容,传给json.loads()的是不完整的无效JSON。 - JSON格式错误:
"the best"后面多了一个空格加双引号,属于无效的JSON字符串闭合方式。
下面是具体的修复方法:
方法一:修正Python字符串定义
如果是在代码里直接定义这个字符串,用三重引号或者转义内部的单引号,同时修正JSON的转义:
# 方式1:转义内部单引号 text = '{"id": "a364ebd4", "reason": "delay", "description": "I bought a tv. It\'s not working and the manager said it was \\"the best\\""}' # 方式2:用三重引号更直观,无需转义单引号 text = '''{"id": "a364ebd4", "reason": "delay", "description": "I bought a tv. It's not working and the manager said it was \\"the best\\""}''' # 现在可以正常解析 import json textf = json.loads(text)
方法二:修复TXT文件中的原始内容
如果是从TXT文件读取的内容,确保文件里的JSON格式正确:
{"id": "a364ebd4", "reason": "delay", "description": "I bought a tv. It's not working and the manager said it was \"the best\""}
注意去掉"the best"后面多余的空格和双引号,读取后直接用json.loads()解析即可。
方法三:批量修复错误字符串(适合大量类似问题)
如果文件里有大量这类转义错误,可以用正则表达式批量修复:
import re import json # 假设从文件读取的错误内容 bad_text = open("your_file.txt", "r").read() # 修复未转义的单引号(如果是Python字符串带来的问题) fixed_text = re.sub(r"(?<!\\)'", r"\'", bad_text) # 修复字符串末尾多余的空格和引号 fixed_text = re.sub(r'(\\"[^"]*\\" )"', r'\1', fixed_text) # 解析 textf = json.loads(fixed_text)
内容的提问来源于stack exchange,提问作者Bea
相关产品推荐
相关产品推荐

