简体   繁体   English

在Python 3上使用json.dumps时,如何添加一些空行?

[英]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. 但是,当我使用json.dumps将此字典保存到文件中时,它将显示为一行。 So it's hard to check and edit. 因此很难检查和编辑。

So how can I save a dictionary use json in more line, and load that? 那么,如何保存字典并在更多行中使用json并加载呢? use str.split when load and dump? 在加载和转储时使用str.split

The API is that you specify the indent you would like for each line: API是您为每行指定缩进:

import json

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

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

No problem! 没问题! json.dumps has some built in options to help out. json.dumps有一些内置选项可以帮助您。

Try doing it like this... 尝试这样做...

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

And write your new string to the file. 并将您的新字符串写入文件。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM