[python] 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'

This question is related to python string

The answer is


Why not do string suppression with triple quotes:

>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes

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'

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}

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