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?
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With