Can't pretty print json from python

Whenever I try to print out json from python, it ignores line breaks and prints the literal string "\n" instead of new line characters.

I'm generating json using jinja2. Here's my code:

print json.dumps(template.render(**self.config['templates'][name]))

It prints out everything in the block below (literally - even the quotes and "\n" strings):

"{\n    \"AWSTemplateFormatVersion\" : \"2010-09-09\",\n    \"Description\" : ... 


I get something like this whenever I try to dump anything but a dict. Even if I try json.loads() then dump it again I get garbage. It just strips out all line breaks.

What's going wrong?


I'm not sure if it is what you're looking for, but this is what I use for pretty-printing json-objects:

def get_pretty_print(json_object):
    return json.dumps(json_object, sort_keys=True, indent=4, separators=(',', ': '))

print get_pretty_print(my_json_obj)

json.dumps() also accepts parameters for encoding, if you need non-ascii support

Need Your Help

Read file with unknown encoding

python file-io encoding character-encoding

I'm trying to load the columns of a file with a strange encoding. Windows appears to have no issues opening it, but Linux complains and I have only been able to open it using the Atom text editor (...

Using the nested element module in cvs task in ant build.xml

ant cvs build.xml wincvs cvsnt

I have problems connecting to CVS using ant build.xml.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.