[英]How to correctly escape double quote (") inside a json string in Python
在 json 文件中,双引号被转义,我不确定这里缺少什么
import json
s = '{"title": "Fetching all Jobs from \"host_name\"."}'
j = json.loads(s)
print(j)
ValueError: Expecting , delimiter: line 1 column 36 (char 35)
你真的需要一个字符串吗?
s = {"title": 'Fetching all Jobs from "host_name".'}
# If you want a string, then here
import json
j = json.dumps(s)
print(j)
回收的价值看起来像这样
{"title": "Fetching all Jobs from \"host_name\"."}
>>> s2 = r'{"title": "Fetching all Jobs from \"host_name\"."}'
>>> json.loads(s2)
{'title': 'Fetching all Jobs from "host_name".'}
使用 r 字符串将帮助您转义 json 字符串中的内引号。
import json
s = r'{"title": "Fetching all Jobs from \"host_name\"."}'
j = json.loads(s)
print(j)
但我不确定这是否是最佳做法。
如果您以这种方式使用json
,它可能对您有用:
import json
s = ‘my string with “double quotes” and more’
json.dumps(s)
'"my string with \\"double quotes\\" and more"'
我知道有两种方法可以处理它,第一种是转义“\”:
s = '{"title": "Fetching all Jobs from \\"host_name\\"."}'
第二种是使用原始字符串文字:
s = r'{"title": "Fetching all Jobs from \"host_name\"."}'
注意字符串前面的“r”。
这将帮助你
>>> import json
>>> s= json.dumps('{"title": "Fetching all Jobs from \"host_name\"."}')
>>> j=json.loads(s)
>>> print(j)
{"title": "Fetching all Jobs from "host_name"."}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.