Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prettyprint a JSON file?

I have a JSON file that is a mess that I want to prettyprint. What's the easiest way to do this in Python?

I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in. Just using the filename doesn't work.

like image 380
Colleen Avatar asked Oct 17 '12 21:10

Colleen


People also ask

How do I beautify JSON in Notepad ++?

Open notepad++ -> ALT+P -> Plugin Manager -> Selcet JSON Viewer -> Click Install. Restart notepad++ Now you can use shortcut to format json as CTRL + ALT +SHIFT + M or ALT+P -> Plugin Manager -> JSON Viewer -> Format JSON.

How do I auto format a JSON file?

The key-map to auto-format the selected JSON is ALT-SHIFT-F. This is the same key-map to auto-format other languages too, so I often find myself doing CTRL-A (for select all text) followed by ALT-SHIFT-F to fix my messy C# code after a series of cut and paste operations.


1 Answers

The json module already implements some basic pretty printing in the dump and dumps functions, with the indent parameter that specifies how many spaces to indent by:

>>> import json >>> >>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]' >>> parsed = json.loads(your_json) >>> print(json.dumps(parsed, indent=4, sort_keys=True)) [     "foo",      {         "bar": [             "baz",              null,              1.0,              2         ]     } ] 

To parse a file, use json.load():

with open('filename.txt', 'r') as handle:     parsed = json.load(handle) 
like image 60
Blender Avatar answered Oct 02 '22 11:10

Blender