Pretty print JSON dumps
I ended up using jsbeautifier:
import jsbeautifieropts = jsbeautifier.default_options()opts.indent_size = 2jsbeautifier.beautify(json.dumps(d), opts)
Output:
{ "a": "blah", "c": [1, 2, 3], "b": "foo"}
Write your own JSON serializer:
import numpyINDENT = 3SPACE = " "NEWLINE = "\n"def to_json(o, level=0): ret = "" if isinstance(o, dict): ret += "{" + NEWLINE comma = "" for k,v in o.iteritems(): ret += comma comma = ",\n" ret += SPACE * INDENT * (level+1) ret += '"' + str(k) + '":' + SPACE ret += to_json(v, level + 1) ret += NEWLINE + SPACE * INDENT * level + "}" elif isinstance(o, basestring): ret += '"' + o + '"' elif isinstance(o, list): ret += "[" + ",".join([to_json(e, level+1) for e in o]) + "]" elif isinstance(o, bool): ret += "true" if o else "false" elif isinstance(o, int): ret += str(o) elif isinstance(o, float): ret += '%.7g' % o elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.integer): ret += "[" + ','.join(map(str, o.flatten().tolist())) + "]" elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.inexact): ret += "[" + ','.join(map(lambda x: '%.7g' % x, o.flatten().tolist())) + "]" else: raise TypeError("Unknown type '%s' for json serialization" % str(type(o))) return retinputJson = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]}print to_json(inputJson)
Output:
{ "a": "blah", "c": [1,2,3], "b": "foo"}
Another alternative is print(json.dumps(d, indent=None, separators=(',\n', ': ')))
The output will be:
{"a": "blah","c": [1,2,3],"b": "foo"}
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 of separators=(', ',': ')
). Note also that the comma separator doesn't distinguish between k/v pairs and list elements.