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?
Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .
We can use the Python json module to pretty-print the JSON data. The json module is recommended to work with JSON files. We can use the dumps() method to get the pretty formatted JSON string.
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With