1

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?

2 Answers 2

1

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. :)

Sign up to request clarification or add additional context in comments.

2 Comments

@KevinGuan No problem Kevin! Please remember to mark one of our answers as correct if they helped you. We'd appreciate it, and it'll help other users who have this issue in the future. Cheers!
Yes I will :). But seems like must 7 minutes later.
1

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
}

1 Comment

All good with me :-) So long as you got the answer you needed. I actually ran into the same thing yesterday myself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.