Python中如何将带反斜杠转义的字符串转换为dict字典
转换带转义嵌套字符串为Python字典方案
问题场景
现有结构中外层字典的list_file字段存储了一段带转义符的类字典格式字符串,需要将该字符串解析为真正的Python字典类型,原始输入结构如下:
resu = { "list_file":"{ \"iross\": [ \"artt\", \"artction\", \"artiong\", \"artiype\", \"coon\", \"colleong\", \"collype\", \"genre\", \"genst\", \"genction\", \"rle\", \"sog\", \"storont\", \"mepe\", ], \"mch\": [\"mach\", \"coltch\", \"stch\"], \"popularity\": [\"album_poe\", \"song_populanre\"] }" }
实现方法
注意内层字符串的列表末尾存在多余尾逗号,不符合标准JSON格式要求,直接使用json.loads会触发解析错误,这里用Python标准库ast的literal_eval方法解析最稳妥:
- 该方法可以原生识别Python字典、列表语法格式,自动兼容尾逗号
- 只会解析合法的Python基础类型字面量,不存在执行恶意代码的安全风险
完整可运行代码
import ast resu = { "list_file": """{ "iross": [ "artt", "artction", "artiong", "artiype", "coon", "colleong", "collype", "genre", "genst", "genction", "rle", "sog", "storont", "mepe", ], "mch": ["mach", "coltch", "stch"], "popularity": ["album_poe", "song_populanre"] }""" } # 解析内层字符串为字典 resu["list_file"] = ast.literal_eval(resu["list_file"]) # 验证解析结果 print(type(resu["list_file"])) # 输出:<class 'dict'> print(resu["list_file"]["mch"]) # 输出:['mach', 'coltch', 'stch']
补充:如果你已经提前清理了内层字符串里的所有尾逗号,确认其符合严格JSON规范,也可以直接用
json.loads(resu["list_file"])完成解析,不需要导入ast库,解析效率更高。
内容的提问来源于stack exchange,提问作者Meryem CHRG
相关产品推荐
相关产品推荐

