Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write one key value pair per line from python dict to a json file? [duplicate]

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?

like image 506
Basj Avatar asked Feb 04 '26 02:02

Basj


2 Answers

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"
}
like image 178
Allen Z. Avatar answered Feb 05 '26 15:02

Allen Z.


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.

like image 32
MarkHu Avatar answered Feb 05 '26 16:02

MarkHu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!