'Compact but pretty JSON output in python?
JSON is written either with indent=None
(default) as a single line (unreadable to a human eye) or with ident=N
with a newline after each comma.
What I would like to see is a more compact but still pretty output, similar to what Common Lisp pretty-printing does. E.g., instead of
{
"cleanup":{
"cpu":6936.780000000001,
"wall":7822.319401979446
},
"finished":"2017-08-14 18:36:23",
"init":{
"cpu":1365.73,
"wall":1380.7802910804749
},
"job":"timings",
"run":{
"cpu":953.6700000000001,
"wall":8350.496850013733
},
"started":"2017-08-14 13:28:06"
}
I would like to see
{
"cleanup":{"cpu":6936.780000000001,"wall":7822.319401979446},
"finished":"2017-08-14 18:36:23",
"init":{"cpu":1365.73,"wall":1380.7802910804749},
"job":"timings",
"run":{"cpu":953.6700000000001,"wall":8350.496850013733},
"started":"2017-08-14 13:28:06"
}
similar to what pprint
produces.
Solution 1:[1]
This is not possible at this time, but when RFE: more compact pretty printing is implemented, this question will be answered by using python-rapidjson.
Solution 2:[2]
I don't know of a tool that already does this, but it isn't hard to make one:
def compact(d):
def tight(obj):
return dumps(obj, separators=(',', ':'))
print('{')
for i, (k, v) in enumerate(d.items()):
comma = ',' if i < len(d) else ''
print(f' {tight(k)}:{tight(v)}{comma}')
print('}')
For your example, this emits:
>>> compact(d)
{
"cleanup":{"cpu":6936.780000000001,"wall":7822.319401979446},
"finished":"2017-08-14 18:36:23",
"init":{"cpu":1365.73,"wall":1380.7802910804749},
"job":"timings",
"run":{"cpu":953.6700000000001,"wall":8350.496850013733},
"started":"2017-08-14 13:28:06",
}
Solution 3:[3]
This won't get it quite as tight as you want, but it is the format I find most satisfying. You can test it online at https://beautifier.io/
pip install jsbeautifier
To use:
import jsbeautifier
print( jsbeautifier.beautify(json.dumps(data)) )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sds |
Solution 2 | Raymond Hettinger |
Solution 3 | Orwellophile |