Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't pretty print json from python

Tags:

python

json

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\" : ... 

(truncated)

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?

like image 574
user1491250 Avatar asked May 01 '13 12:05

user1491250


People also ask

How do I print JSON data in Python?

First, use json. loads() method to convert JSON String to Python object. To convert this object to a pretty print JSON string, the json. dumps() method is used.

What is JSON pretty format?

Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .


2 Answers

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.

like image 128
felixbr Avatar answered Sep 20 '22 22:09

felixbr


json.dumps() returns a JSON-encoded string. The JSON standard mandates that newlines are encoded as \\n, which is then printed as \n:

>>> s="""hello
... there"""
>>> s
'hello\nthere'
>>> json.dumps(s)
'"hello\\nthere"'
>>> print(json.dumps(s))
"hello\nthere"

There's not much you can do to change that if you want to keep a valid JSON string. If you want to print it, the correct way would be to print the JSON object, not its string representation:

>>> print(s)
hello
there
>>> print(json.loads(json.dumps(s)))  # pointless; just for demonstration...
hello
there
like image 43
Tim Pietzcker Avatar answered Sep 22 '22 22:09

Tim Pietzcker