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
Your data is poorly formed. The value fields in particular have numerous spaces and new lines. Automated formatters won't work on this, as they will not modify the actual data. As you generate the data for output, filter it as needed to avoid the spaces.
A minimal in-python solution that colors json data supplied via the command line:
import sys
import json
from pygments import highlight, lexers, formatters
formatted_json = json.dumps(json.loads(sys.argv[1]), indent=4)
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)
Inspired by pjson
mentioned above. This code needs pygments
to be installed.
Output example:
With jsonlint (like xmllint):
aptitude install python-demjson
jsonlint -f foo.json
You could pipe the output to jq. If you python script contains something like
print json.dumps(data)
then you can fire:
python foo.py | jq '.'
From the command-line:
echo '{"one":1,"two":2}' | python -mjson.tool
which outputs:
{
"one": 1,
"two": 2
}
Programmtically, the Python manual describes pretty-printing JSON:
>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
"4": 5,
"6": 7
}
The cli command I've used with python for this is:
cat myfile.json | python -mjson.tool
You should be able to find more info here:
http://docs.python.org/library/json.html