Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 384
Caz Avatar asked Sep 05 '25 03:09

Caz


1 Answers

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))
like image 134
Martijn Pieters Avatar answered Sep 07 '25 19:09

Martijn Pieters