如何修复无效JSON中特定重复双引号且保留空值?
修复带重复双引号的不合法JSON字符串
先看这个存在语法问题的JSON字符串:
example = '{"Hello": "world", "key_1": ""Double quote text"", "key_2", ""}'
这不是合法的JSON对象,执行json.loads(example)会抛出错误:
JSONDecodeError: Expecting ',' delimiter: line 1 column 29 (char 28)
直接用example.replace('""', '"')虽然能修复key_1的重复引号问题,但会把key_2的空值""变成",破坏空值结构。
解决方案:用正则表达式精准替换
使用正则表达式只匹配中间包含非空内容的重复双引号对,保留单独的""(空值):
import re import json example = '{"Hello": "world", "key_1": ""Double quote text"", "key_2", ""}' # 先修正key_2的语法错误(原字符串中逗号应为冒号) fixed_str = example.replace('"key_2",', '"key_2":') # 替换中间有内容的重复双引号 fixed_str = re.sub(r'""([^"]+)""', r'"\1"', fixed_str) # 验证结果 print(fixed_str) # 输出: {"Hello": "world", "key_1": "Double quote text", "key_2": ""} data = json.loads(fixed_str) print(data) # 输出: {'Hello': 'world', 'key_1': 'Double quote text', 'key_2': ''}
正则说明
""([^"]+)"" 匹配规则:
- 开头和结尾都是连续两个双引号
- 中间
([^"]+)捕获至少一个非双引号的字符(确保是有内容的重复引号) - 替换为
"\1",即用单个双引号包裹捕获到的内容,只修复有实际文本的重复引号,不改动空值的""。
内容的提问来源于stack exchange,提问作者adrpino
相关产品推荐
相关产品推荐

