Can someone suggest how I can beautify JSON in Python or through the command line?
The only online based JSON beautifier which could do it was: http://jsonviewer.stack.h
Use the python tool library
Command line: python -mjson.tool
In code: http://docs.python.org/library/json.html
First install pygments
then
echo '<some json>' | python -m json.tool | pygmentize -l json
I didn't like the output of json.dumps(...) -> For my taste way too much newlines. And I didn't want to use a command line tool or install something. I finally found Pythons pprint (= pretty print). Unfortunately it doesn't generate proper JSON but I think it is useful to have a user friendly glympse at the stored data.
Output of json.dumps(json_dict, indent=4)
{
"hyperspace": {
"constraints": [],
"design": [
[
"windFarm.windparkSize.k",
"continuous",
[
0,
0,
5
]
],
[
"hydroPlant.primaryControlMax",
"continuous",
[
100,
300
]
]
],
"kpis": [
"frequency.y",
"city.load.p[2]"
]
},
"lhc_size": 10,
"number_of_runs": 10
}
Usage of pprint:
import pprint
json_dict = {"hyperspace": {"constraints": [], "design": [["windFarm.windparkSize.k", "continuous", [0, 0, 5]], ["hydroPlant.primaryControlMax", "continuous", [100, 300]]], "kpis": ["frequency.y", "city.load.p[2]"]}, "lhc_size": 10, "number_of_runs": 10}
formatted_json_str = pprint.pformat(json_dict)
print(formatted_json_str)
pprint.pprint(json_dict)
Result of pprint.pformat(...)
or pprint.pprint(...)
:
{'hyperspace': {'constraints': [],
'design': [['windFarm.windparkSize.k', 'continuous', [0, 0, 5]],
['hydroPlant.primaryControlMax',
'continuous',
[100, 300]]],
'kpis': ['frequency.y', 'city.load.p[2]']},
'lhc_size': 10,
'number_of_runs': 10}
Try underscore-cli:
cat myfile.json | underscore print --color
It's a pretty nifty tool that can elegantly do a lot of manipulation of structured data, execute js snippets, fill templates, etc. It's ridiculously well documented, polished, and ready for serious use. And I wrote it. :)
Use the indent
argument of the dumps
function in the json module.
From the docs:
>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
"4": 5,
"6": 7
}
alias jsonp='pbpaste | python -m json.tool'
This will pretty print JSON that's on the clipboard in OSX. Just Copy it then call the alias from a Bash prompt.