Remi Guan
Remi Guan

Reputation: 22292

How to add some empty line when using `json.dumps` on Python 3?

For example, I have a dictionary like this:

d = {'Name': 'Jone', 'Job': 'Boss', 'From': 'England', (and many many more...)}

As you can see, this dictionary is very very long. so I can display it in my code like this:

 a = {'Name': 'Jone',
      'Job': 'Boss',
      'From': 'England',
      (and many many more...)}

But when I using json.dumps to save this dictionary in a file, it will display as one line. So it's hard to check and edit.

So how can I save a dictionary use json in more line, and load that? use str.split when load and dump?

Upvotes: 1

Views: 1605

Answers (2)

pmccallum
pmccallum

Reputation: 808

No problem! json.dumps has some built in options to help out.

Try doing it like this...

string = json.dumps(d, indent=4, sort_keys=True)

And write your new string to the file. :)

Upvotes: 1

Aidan Kane
Aidan Kane

Reputation: 4006

The API is that you specify the indent you would like for each line:

import json

print(json.dumps(dict(a=1, b=2), indent='    '))

{
    "a": 1,
    "b": 2
}

Upvotes: 1

Related Questions