Python中如何将无引号的嵌套字符串字典转换为标准字典
无引号嵌套字符串转Python字典解决方案
核心思路
你拿到的原始内容是带HTML转义字符的JavaScript对象格式数据,无需手动逐行修改,通过字符解码+格式修正+类型转换三步即可完成转换,自动适配你要求的数值类型转换、空值保留规则。
无第三方依赖实现方案
import re import ast import html # 此处替换为你实际拿到的原始字符串 raw_str = """ { id: 0, label: 'Data0', axis: "left", color: "#0000ff", avg: "383.04347826086956", last: "378.0", min: "282.0", max: "439.0" } , { id: 1, label: 'Data1', axis: "left", color: "#00ff00", avg: "", last: "", min: "", max: "" } """ # 1. 解码HTML转义字符,把"转为普通双引号 decoded_str = html.unescape(raw_str) # 2. 正则匹配无引号的键,统一添加双引号 formatted_str = re.sub(r'(\w+)(?=:)', r'"\1"', decoded_str) # 3. 把单引号替换为双引号,统一字符串包裹格式 formatted_str = formatted_str.replace("'", '"') # 4. 转换为Python字典列表,自动完成数值类型转换 result = ast.literal_eval(f"[{formatted_str}]")
输出验证
转换后输出结果完全符合预期:
print(result[0]) # {'id': 0, 'label': 'Data0', 'axis': 'left', 'color': '#0000ff', 'avg': 383.04347826086956, 'last': 378.0, 'min': 282.0, 'max': 439.0} print(result[1]) # {'id': 1, 'label': 'Data1', 'axis': 'left', 'color': '#00ff00', 'avg': '', 'last': '', 'min': '', 'max': ''}
兼容复杂格式的可选方案
如果原始数据键名包含特殊字符、正则匹配容易出错,可以使用专门解析非标准JSON的demjson3库处理:
- 安装依赖:
pip install demjson3 - 代码实现:
import demjson3 import html decoded_str = html.unescape(raw_str) result = demjson3.decode(f"[{decoded_str}]")
内容的提问来源于stack exchange,提问作者Ribhujeet Das
相关产品推荐
相关产品推荐

