I use this code to pretty print some dict
into JSON :
import json
d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]}
print json.dumps(d, indent = 2, separators=(',', ': '))
Output :
{
"a": "blah",
"c": [
1,
2,
3
],
"b": "foo"
}
This is a little bit too much (newline for each list element!).
Which syntax should I use to have ...
{
"a": "blah",
"c": [1, 2, 3],
"b": "foo"
}
instead ?
Write your own JSON serializer:
Output:
Perhaps not quite as efficient, but consider a simpler case (somewhat tested in Python 3, but probably would work in Python 2 also):
This might give you some ideas, short of writing your own serializer completely. I used my own favorite indent technique, and hard-coded ensure_ascii, but you could add parameters and pass them along, or hard-code your own, etc.
Another alternative is
print json.dumps(d, indent = None, separators=(',\n', ': '))
The output will be:
Note that though the official docs at https://docs.python.org/2.7/library/json.html#basic-usage say the default args are
separators=None
--that actually means "use default ofseparators=(', ',': ')
). Note also that the comma separator doesn't distinguish between k/v pairs and list elements.This has been bugging me for a while as well, I found a 1 liner I'm almost happy with:
That essentially convert all lists or tuples to a string, then uses json.dumps with indent to format the dict. Then you just need to remove the quotes and your done!
Note: I convert the dict to string to easily convert all lists/tuples no matter how nested the dict is.
PS. I hope the Python Police won't come after me for using eval... (use with care)
I ended up using jsbeautifier:
Output: