How to store python dict in json file from mutiple runs?

Viewed 38

I am trying to store user inputted data inside of a dict into a .json file. I am using

d = data
with open('file.json', 'a') as save_file:
     convert_file.write(json.dumps(d))

But when I try to print the data with

with open('file.json') as f:
     filedata = [json.loads(line) for line in f]
print(filedata)    

I get an error, because of the messed up json file.

{"dict1": {"a": ["1", "2"], "Name": "test"}}{"dict2": {"a": ["3", "4"], "Name": "test2"}}

How can I write my dictionaries to the file without messing up the formatting?

1 Answers

Add a line break between json strings:

d = data
with open('file.json', 'a') as save_file:
     convert_file.write(json.dumps(d) + '\n')

This format you are using is the json lines format. You place one valid json in each line, therefore the line break.

Related