首页 > 解决方案 > 正确删除字符串到 json 格式的额外引号

问题描述

例如:我有一个字符串

{"key": {"value": "this," is the "value" of guy""}}

我希望这个字符串以某种格式出现,以便我可以使用 python 的 json.loads 函数加载它。

{"key": {"value": "this, is the value of guy"}}

是否有任何内置的python函数可以做到这一点或任何正则表达式,我尝试了许多正则表达式,但随着时间的推移,不同的字符串变得更糟。

标签: pythonjsondictionary

解决方案


您可以使用re.sub前瞻模式来匹配后跟冒号或右括号的引号对,并从外引号中的内容中去除引号:

import re
s = '{"key": {"value": "this," is the "value" of guy""}}'
print(re.sub(r'"(.*?)"(?=\s*[:}\]])', lambda m: '"%s"' % m.group(1).replace('"', ''), s))

这输出:

{"key": {"value": "this, is the value of guy"}}

推荐阅读