Dump two dictionaries in a json file on separate lines

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?

Mar*_*ers 5

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)