Pretty print JSON dumps

29,763

Solution 1

After years, I found a solution with the built-in pprint module:

import pprint
d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]}
pprint.pprint(d)                    # default width=80 so this will be printed in a single line
pprint.pprint(d, width=20)          # here it will be wrapped exactly as expected

Output:

{'a': 'blah',  
 'b': 'foo',  
 'c': [1, 2, 3]}

Solution 2

I ended up using jsbeautifier:

import jsbeautifier
opts = jsbeautifier.default_options()
opts.indent_size = 2
jsbeautifier.beautify(json.dumps(d), opts)

Output:

{
  "a": "blah",
  "c": [1, 2, 3],
  "b": "foo"
}

Solution 3

Write your own JSON serializer:

import numpy

INDENT = 3
SPACE = " "
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 ret

inputJson = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]}
print to_json(inputJson)

Output:

{
   "a": "blah",
   "c": [1,2,3],
   "b": "foo"
}

Solution 4

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.

Share:
29,763
Basj
Author by

Basj

I work on R&D involving Python, maths, machine learning, deep learning, data science, product design, and MacGyver solutions to complex problems. I love prototyping, building proofs-of-concept. For consulting/freelancing inquiries : [email protected]

Updated on July 30, 2022

Comments

  • Basj
    Basj over 1 year

    I use this code to pretty print a 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 this:

    {
      "a": "blah",
      "c": [1, 2, 3],
      "b": "foo"
    }
    

    instead?