Caz
Caz

Reputation: 43

Dump two dictionaries in a json file on separate lines

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)

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?

Upvotes: 4

Views: 2719

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121436

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)

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))

Upvotes: 5

Related Questions