Escape double quotes for JSON in Python

Question:

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'
Asked By: aschmid00

||

Answers:

>>> 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
>>> 
Answered By: Andrew

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"'
Answered By: zeekay

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}
Answered By: Medhat Gayed

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'
Answered By: Tam Nguyen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.