Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 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 Answer

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"}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...