[Solved] Escape double quotes for JSON in Python

How can I replace double quotes with a backslash and double quotes in Python?

>>> s = 'my string with "double quotes" blablabla'
>>> s.replace('"', '\"')
'my string with \"double quotes\" blablabla'
>>> s.replace('"', '\"')
'my string with \"double quotes\" blablabla'

I would like to get the following:

'my string with "double quotes" blablabla'

Solution #1:

>>> s = 'my string with \"double quotes\" blablabla'
>>> s
'my string with \"double quotes\" blablabla'
>>> print s
my string with "double quotes" blablabla
>>> 

When you just ask for ‘s’ it escapes the for you, when you print it, you see the string a more ‘raw’ state. So now…

>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
>>> print s.replace('"', '\"')
my string with "double quotes" blablabla
>>> 
Respondent: Andrew

Solution #2:

You should be using the json module. json.dumps(string). It can also serialize other python data types.

import json

>>> s = 'my string with "double quotes" blablabla'

>>> json.dumps(s)
<<< '"my string with \"double quotes\" blablabla"'
Respondent: zeekay

Solution #3:

Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:

>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\"x\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}
Respondent: Medhat Gayed

Solution #4:

i know this question is old, but hopefully it will help someone.
i found a great plugin for those who are using PyCharm IDE:
string-manipulation
that can easily escape double quotes (and many more…), this plugin is great for cases where you know what the string going to be.
for other cases, using json.dumps(string) will be the recommended solution

str_to_escape = 'my string with "double quotes" blablabla'

after_escape = 'my string with "double quotes" blablabla'
Respondent: Tam Nguyen

Solution #5:

Why not do string suppression with triple quotes:

>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes
Respondent: inspectorG4dget

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.