Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

python - JSON: save one dict per line

How do I save a list of python dictionaries to a file, where each dictwill be saved in one line? I know I can use json.dump to save the list of dictionaries. But I can only save the list in compact form (the full list in one line) or indented, where for all dictionaries keys a newline is added.

EDIT:

I want my final json file to look like this:

[{key1:value,key2:value},
{key1:value,key2:value},
...
{key1:value,key2:value}]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I agree with another response -- the best you can do is to json.dump each dict individually and write the commas and newlines manually. Here is how I would do that:

import json

data = [
    {"key01":"value","key02":"value"},
    {"key11":"value","key12":"value"},
    {"key21":"value","key22":"value"}
]

import json
with open('file.json', 'w') as fp:
    fp.write(
        '[' +
        ',
'.join(json.dumps(i) for i in data) +
        ']
')

Result:

[{"key01": "value", "key02": "value"},
{"key12": "value", "key11": "value"},
{"key22": "value", "key21": "value"}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...