Forums

appending to json file

Hello to everyone

I have question

def write_json(data, filename='answer.json'):
    with open(filename,'w') as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

with this code, I created the file answer.txt, which appears in my default directory (directory after home)

The problem is, that I want to append to existing json file another json data. but it's not working

with open('/home/***/answer.json') as json_file:
    old_data= json.load(json_file)
    newdata.update(old_data)
write_json(newdata)

Can you help me?

Are you overwriting old_data in the second line of your second code fragment?

thanks solved

with open(filename,'w') as f:

instead of w put a+

Yup, that should do the trick :-)

If you append to .json file, most likely it will not parse as JSON anymore. Instead you need to read/parse it, then make changes to it's object representation as dicts/lists, then serialize back to string and (over)write the whole file. Read more...

That's an excellent point.