Caz*_*Caz 4 python json dictionary dump
This is my code:
import json
data1 = {"example1":1, "example2":2}
data2 = {"example21":21, "example22":22}
with open("saveData.json", "w") as outfile:
json.dump(data1, outfile)
json.dump(data2, outfile)
Run Code Online (Sandbox Code Playgroud)
The output is this:
{"example2": 2, "example1": 1}{"example21": 21, "example22": 22}
When I want the output to be this:
{"example2": 2, "example1": 1}
{"example21": 21, "example22": 22}
So how do I dump data1 and data2 dictionaries to the same json file on two separate lines?
You'll need to write a newline between them; just add a .write('\n') call:
with open("saveData.json", "w") as outfile:
json.dump(data1, outfile)
outfile.write('\n')
json.dump(data2, outfile)
Run Code Online (Sandbox Code Playgroud)
This produces valid JSON lines output; load the data again by iterating over the lines in the file and using json.loads():
with open("saveData.json", "r") as infile:
data = []
for line in infile:
data.append(json.loads(line))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2618 次 |
| 最近记录: |