Thursday 15 December 2016

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


Answer




The json module already implements some basic pretty printing with the indent parameter:



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...