python - 正确删除字符串到 json 格式的额外引号
问题描述
例如:我有一个字符串
{"key": {"value": "this," is the "value" of guy""}}
我希望这个字符串以某种格式出现,以便我可以使用 python 的 json.loads 函数加载它。
{"key": {"value": "this, is the value of guy"}}
是否有任何内置的python函数可以做到这一点或任何正则表达式,我尝试了许多正则表达式,但随着时间的推移,不同的字符串变得更糟。
解决方案
您可以使用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"}}
推荐阅读
- python - 如何从 Qdialog 窗口返回
- python - 无法在 Gcloud 上部署 Django 项目
- java - 从 Scala 访问 HBase 时发生了非法反射访问操作
- javascript - Wordpress 使用 javascript 更改 iframe src
- c# - Hangfire、EF dbContext 和 JSON 参考循环
- android - 在深度打盹模式测试中未收到 FCM 高优先级消息
- javascript - 在 JS/ES6 中获取枚举键的文字字符串
- amazon-web-services - 如何创建一个蟒蛇蛋?并火花提交
- javascript - Javascript 对象变量常量
- mongodb - 如何优化聚合查询以根据不同的键进行分组?