You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将值含双引号的JSON字符串转换为Python字典

处理含未转义双引号的无效JSON字符串(Python)

现有一段无效JSON,因description字段内包含未转义的双引号导致格式非法,且无法修改源文件,需要用Python处理后通过json.loads()正常解析,能否用正则表达式处理这些内部双引号?

原始无效JSON:

{
    "@context": "http://schema.org",
    "@type": "Product",
    "name": "ADIZERO ADIOS PRO 2 Löparskor",
    "@id": "adidas-adizero-adios-pro-2-loparskor",
    "color": "Lila",
    "description": "Example text "Best Comfort" an other example text.",
    "brand": {
    "@type": "Thing",
    "name": "adidas"
    },
    "audience": {
    "@type": "Audience",
    "name": "Herr, Dam"
    }        
}

解决方案:正则表达式处理内部未转义双引号

完全可以用正则处理,针对这个场景,我们可以精准定位description字段值内的未转义双引号,选择去除或者转义。

代码示例(去除内部双引号)

import json
import re

# 原始无效JSON字符串
invalid_json = '''{
    "@context": "http://schema.org",
    "@type": "Product",
    "name": "ADIZERO ADIOS PRO 2 Löparskor",
    "@id": "adidas-adizero-adios-pro-2-loparskor",
    "color": "Lila",
    "description": "Example text "Best Comfort" an other example text.",
    "brand": {
    "@type": "Thing",
    "name": "adidas"
    },
    "audience": {
    "@type": "Audience",
    "name": "Herr, Dam"
    }        
}'''

# 正则匹配description字段值内的内容,移除其中的双引号
pattern = r'(?<="description": ")(.*?)(?=")'
def clean_inner_quotes(match):
    return match.group(0).replace('"', '')

processed_json = re.sub(pattern, clean_inner_quotes, invalid_json)

# 尝试解析
try:
    parsed_data = json.loads(processed_json)
    print("解析成功,处理后的description:")
    print(parsed_data['description'])
except json.JSONDecodeError as e:
    print(f"解析失败:{str(e)}")

可选方案:转义内部双引号

如果想保留原文本的引号语义,只是让JSON合法,可以把替换逻辑改成转义双引号:

def escape_inner_quotes(match):
    return match.group(0).replace('"', '\\"')

注意事项

  • 上面的正则是针对description单个字段的场景,如果其他字段也有类似问题,需要调整正则逻辑,比如匹配所有字符串值内的未转义双引号(要注意区分字段名的引号和值内的引号,避免误改)。
  • 正则处理JSON属于临时适配方案,只适合这种格式固定、问题单一的场景,如果JSON结构复杂或者有更多异常情况,建议使用容错性更强的第三方JSON解析库(比如demjson、json5)。

内容的提问来源于stack exchange,提问作者Tanhaeirad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:05:17