Python:如何转义json字符串值内的双引号? [英] Python: How to escape double quote inside json string value?

查看:1510
本文介绍了Python:如何转义json字符串值内的双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中解析json字符串时遇到问题,因为在像{"name": "Jack O"Sullivan", "id": "1"}

I'm having trouble parsing a json string in python because there are extra double quotes inside the string values like {"name": "Jack O"Sullivan", "id": "1"}

我正在尝试将其转换为列表,以便进一步评估,例如:

I'm trying to convert it into list for further evaluation like so:

import ast
js = '{"name": "Jack O"Sullivan", "id": "1"}'
ast.literal_eval(js).values()  

如何将json字符串更改为这样的"Jack O\'Sullivan",以便正确评估.

How do I change the json string to be something like this "Jack O\'Sullivan", so that it evaluated properly.

编辑请仅强调一下,我知道json无效,但这是我所拥有的,更改源不是一种选择.我目前正在努力解决此限制.

Edit Just to stress that I know the json is invalid but this is what I've got and changing the source is NOT an option. I'm looking to work around this limitation at the moment.

推荐答案

import re

json = '{"name": "Jack O"Sullivan", "id": "1"}'

fixed = re.sub(r'("[\s\w]*)"([\s\w]*")',r"\1\'\2", json)

我怀疑这会起作用(在 repl.it 上的工作示例),它使用以下正则表达式:

I suspect this will work (working example at repl.it), it uses the following regex:

("[\s\w]*)"([\s\w]*")

,然后将任何内部"替换为\'.只要包含列表是有效的([\s\w]),这将起作用,即有效的字符串将仅包含空格和单词字符.您可能不得不为更复杂的名称添加其他可能性.

and then replacing any inner " with \'. This will work as long as the inclusion list is valid (the [\s\w]), ie valid strings will only include spaces and word characters. You may have to add additional possibilities for more complex names.

它与任何字符串"<alpha/space>"<alpha/space>"匹配,然后使用捕获组和反向引用将其替换为"<whatwasbefore>\'<whatwasafter>".

It matches any string "<alpha/space>"<alpha/space>" and then replaces it with "<whatwasbefore>\'<whatwasafter>" using capture groups and back references.

请参见 regex101

正如我在评论中提到的,替代方法是使其排除json控制字符[^{}:,].这应该会产生相似的结果,但不会遗漏其中包含其他字符的名称(例如-).

As I mentioned in the comments, the alternative is to make it exclude json control characters [^{}:,]. This should produce similar results, but won't miss names with other characters in them (like -, for example).

这篇关于Python:如何转义json字符串值内的双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆