Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pretty-print json in python (pythonic way)

Tags:

python

json

I know that the pprint python standard library is for pretty-printing python data types. However, I'm always retrieving json data, and I'm wondering if there is any easy and fast way to pretty-print json data?

No pretty-printing:

import requests r = requests.get('http://server.com/api/2/....') r.json() 

With pretty-printing:

>>> import requests >>> from pprint import pprint >>> r = requests.get('http://server.com/api/2/....') >>> pprint(r.json()) 
like image 879
autorun Avatar asked May 18 '14 05:05

autorun


People also ask

How do I beautify JSON output in Python?

To write a Python object as JSON formatted data into a file, json. dump() method is used. Like json. dumps() method, it has the indents and separator parameters to write beautified JSON.

How do I display pretty JSON?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

How do I enable pretty print JSON?

To enable this feature we need to call the enable() method of the ObjectMapper and provide the feature to be enabled. ObjectMapper mapper = new ObjectMapper(). enable(SerializationFeature. INDENT_OUTPUT); String json = mapper.


2 Answers

Python's builtin JSON module can handle that for you:

>>> import json >>> a = {'hello': 'world', 'a': [1, 2, 3, 4], 'foo': 'bar'} >>> print(json.dumps(a, indent=2)) {   "hello": "world",   "a": [     1,     2,     3,     4   ],   "foo": "bar" } 
like image 116
svvac Avatar answered Oct 14 '22 19:10

svvac


import requests import json r = requests.get('http://server.com/api/2/....') pretty_json = json.loads(r.text) print (json.dumps(pretty_json, indent=2)) 
like image 34
Holmes Avatar answered Oct 14 '22 19:10

Holmes