Pretty print JSON dumps

Basj picture Basj · Feb 18, 2014 · Viewed 22.3k times · Source

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?

Answer

Allen Z. picture Allen Z. · Jun 4, 2018

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"
}