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

Strange formatting on append – JSON

recently I have been working on a project, and I needed to append a list of dictionaries to my existing JSON file. But it behaves somewhat strangely.

Here is what I have:

def write_records_to_json(json_object):
    with open("tracker.json", "r+") as f:
        json_file = json.load(f)
        json_file.append(json_object)
        print(json_file)

This is the object I’m trying to append(The object is formatted this way):

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

[
    {
        "file": "dnc_complaint_numbers_2021-12-03.csv",
        "date": "2021-12-03"
    }
]

And this is what I get(Pay attention to the end):
Excuse me please, for not having it more readable.

[{'file': 'dnc_complaint_numbers_2021-12-01.csv', 'date': '2021-12-01'}, {'file': 'dnc_complaint_numbers_2021-12-02.csv', 'date': '2021-12-02'}, '[\n    {\n        "file": "dnc_complaint_numbers_2021-12-03.csv",\n        "date": "2021-12-03"\n    }\n]']

Can someone tell me why is that and how to fix it? Thanks a lot.

>Solution :

From your code and output, we can infer that json_object refers to a string. This string contains JSON. json_file is not JSON, it is a list that is deserialised from JSON.

If you want to add json_object to json_file you should first deserialise the former:

json_file.extend(json.loads(json_object))

You also want to use extend instead of append here, so it is on the same level as the rest of the data.

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