Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

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)

like image 600
rmsrini Avatar asked Nov 01 '25 06:11

rmsrini


2 Answers

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".'}
like image 153
OneCricketeer Avatar answered Nov 02 '25 19:11

OneCricketeer


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.

like image 45
chumbaloo Avatar answered Nov 02 '25 19:11

chumbaloo