user1491250 user1491250 - 11 months ago 101
JSON Question

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?


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.