Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty print JSON dumps

I use this code to pretty print a dict into JSON:

import json d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]} print json.dumps(d, indent = 2, separators=(',', ': ')) 

Output:

{   "a": "blah",   "c": [     1,     2,     3   ],   "b": "foo" } 

This is a little bit too much (newline for each list element!).

Which syntax should I use to have this:

{   "a": "blah",   "c": [1, 2, 3],   "b": "foo" } 

instead?

like image 366
Basj Avatar asked Feb 18 '14 22:02

Basj


People also ask

What is pretty print JSON?

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 .

How do I show pretty JSON in Python?

We can use the Python json module to pretty-print the JSON data. The json module is recommended to work with JSON files. We can use the dumps() method to get the pretty formatted JSON string.


1 Answers

I ended up using jsbeautifier:

import jsbeautifier opts = jsbeautifier.default_options() opts.indent_size = 2 jsbeautifier.beautify(json.dumps(d), opts) 

Output:

{   "a": "blah",   "c": [1, 2, 3],   "b": "foo" } 
like image 139
Allen Z. Avatar answered Sep 24 '22 02:09

Allen Z.