Python escape quotes in json string

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'

Python escape quotes in json string

phwd

20k5 gold badges49 silver badges78 bronze badges

asked May 13, 2011 at 19:48

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

Python escape quotes in json string

answered May 13, 2011 at 19:56

Python escape quotes in json string

zeekayzeekay

50.6k13 gold badges107 silver badges105 bronze badges

4

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 Sep 9, 2013 at 3:43

Medhat GayedMedhat Gayed

2,32718 silver badges11 bronze badges

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

answered May 13, 2011 at 19:54

AndrewAndrew

2,50416 silver badges9 bronze badges

6

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 Feb 20, 2021 at 17:11

Python escape quotes in json string

Not the answer you're looking for? Browse other questions tagged python string or ask your own question.

If you have a JSON formatted file, and you want to put it in the form of a string, with double quotes and newlines escaped, it’s a pain to do this manually. Note: if all you want to do is read in or print out JSON formatted text, then you can simply use the json library.

In my case I wanted to copy the JSON from an API guide, and automatically convert it to an escaped string.

The key line to escape quotes and new lines is:

outstr = jsonstr.replace('"', '\\"').replace('\n', '\\n')

If you need convert more than 2 characters there’s an interesting discussion about which is the most efficient method on Stackoverflow: Multiple character replace with python.

Here’s my Python script that takes a JSON file name as a command line argument and prints out the escaped string. It checks if the file exists, though doesn’t check that it is a valid JSON file..

# json2string.py - Python script to convert a formatted JSON file into a
#   string with escaped quotes and linefeeds for use in a REST call
#
# Usage: python json2string filename

import sys
import os.path

def usage():
    sys.exit('Usage: python ' + sys.argv[0] + ' filename')

# check for single command argument    
if len(sys.argv) != 2:
    usage()

jsonfile = sys.argv[1]

# check file exists
if os.path.isfile(jsonfile) is False:
    print('File not found: ' + jsonfile)
    usage()

# get a file object and read it in as a string
fileobj = open(jsonfile)
jsonstr = fileobj.read()
fileobj.close()

# do character conversion here
outstr = jsonstr.replace('"', '\\"').replace('\n', '\\n')

# print the converted string
print(outstr)

This entry was posted in Python and tagged Python. Bookmark the permalink.

How do you escape a quote in JSON?

Backspace to be replaced with \b..
Form feed to be replaced with \f..
Newline to be replaced with \n..
Carriage return to be replaced with \r..
Tab to be replaced with \t..
Double quote to be replaced with \".
Backslash to be replaced with \\.

How do you escape a double quote in JSON Python?

replace('"', '\\"') , you have to guess what's going on. Sometimes with imbedded python you might not have access to all the imports. -1 in favour of json. dumps(string) as it's simpler and cleaner.

How do you escape quotes in Python?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.

How do I pass a string with double quotes in JSON?

if you want to escape double quote in JSON use \\ to escape it.