Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add json to a file python

I have this python code:

import json
def write_json(new_data, filename='test.json'):
    with open(filename,'r+') as file:
        file_data = json.load(file)
        file_data.append(new_data)
        file.seek(0)
        json.dump(file_data, file, indent = 4)
e = {
    "1": [
    {
        "id": "df8ec0tdrhseragerse4-a3e0-8aa2da5119d3",
        "name": "Deezomiro"
    }
    ]
}
write_json(e)

Which should add this json to the end of the current test.json file. However, when I run it I get this error.

Traceback (most recent call last):
  File "C:\Users\ArtyF\AppData\Roaming\Microsoft\Windows\Network Shortcuts\HWMonitor\copenheimer\test.py", line 16, in <module>
    write_json(e)
  File "C:\Users\ArtyF\AppData\Roaming\Microsoft\Windows\Network Shortcuts\HWMonitor\copenheimer\test.py", line 5, in write_json
    file_data.append(new_data)
AttributeError: 'dict' object has no attribute 'append'

How can I make this code add this json to the end of the file?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As the error says, dictionaries don’t have append. They do have update.

file_data.update(new_data)
# TODO: dump file_data back to file
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading