简体   繁体   中英

How to correctly escape double quote (") inside a json string in Python

In the json file double quotes are escaped, am not sure what is that am missing here

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)

Do you really need a string in the first place?

s = {"title": 'Fetching all Jobs from "host_name".'}

# If you want a string, then here
import json
j = json.dumps(s)
print(j)

The recycled value looks like so

{"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".'}

Using r strings will help you escape the inner quotes in the json string.

import json
s = r'{"title": "Fetching all Jobs from \"host_name\"."}'
j = json.loads(s)
print(j)

But I am not sure if this is best practice.

if you use json in this way, it might work for you:

import json

 s = ‘my string with “double quotes” and more’
json.dumps(s)
'"my string with \\"double quotes\\" and more"'

There are two ways I know of to handle it, the first is to escape the '\':

s = '{"title": "Fetching all Jobs from \\"host_name\\"."}'

The second is to use a raw string literal:

s = r'{"title": "Fetching all Jobs from \"host_name\"."}'

note the 'r' in front of the string.

this wiil help you

>>> 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"."}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM