简体   繁体   中英

Transfer list of dictionaries from python to json file

I have a list of dictionaries in python with the format:

[{key1a: value1a, key2a: values2a}, {key1b: value1b, key2b: values2b}, ...]

I need to create a json file with the format:

Line 1: {key1a: value1a, key2a: values2a}

Line 2: {key1b: value1b, key2b: values2b} ...

I know that I can write json files with:

with open('data.json', 'w') as outfile:
    json.dump(data_json, outfile)

But I need the exact format I described, without ',' separation between lines and [..] brackets.

I am not sure if this is what you are looking for but here it is:

s = [{"key1a": "value1a", "key2a": "values2a"}, {"key1b": "value1b", "key2b": "values2b"}]

with open("data.json", "w+") as f:
    for i in s:
        json.dump(i, f)
        f.write("\n")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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