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.
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.
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.
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)
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