Convert JSON to escaped string in Python

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

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

jsonfile = sys.argv[1]

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

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

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

# print the converted string

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

One Response to Convert JSON to escaped string in Python

  1. arma says:

    import json

    >>> s = ‘my string with “double quotes” and more’

    >>> json.dumps(s)
    <<< '"my string with \\"double quotes\\" and more"'

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s