rmsrini
rmsrini

Reputation: 43

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)

Upvotes: 4

Views: 8981

Answers (5)

Ananthu A Nair
Ananthu A Nair

Reputation: 337

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"'

Upvotes: 0

Ananthu A Nair
Ananthu A Nair

Reputation: 337

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

Upvotes: 0

Alterlife
Alterlife

Reputation: 6625

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.

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 191953

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

Upvotes: 3

chumbaloo
chumbaloo

Reputation: 721

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.

Upvotes: 3

Related Questions