Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append new data to json file in python

I have bellow json array in a data.json file

[{"type": "Even", "id": 1}, {"type": "Odd", "id": 2}, {"type": "Even", "id": 3}]

and i was trying to append new data to this json file using this code

    def foo(filename, dict_data):
    with open(filename, 'r') as json_data: 
        data = json.load(json_data)

    data.append(dict_data)

    with open(filename, 'w') as json_data: 
        json.dump(data, json_data)

    foo('data.json', lst)

but I'm getting this result

[{"id": 1, "type": "Even"}, {"id": 2, "type": "Odd"}, {"id": 3, "type": "Even"}, [{"id": 4, "type": "Even new"}, {"id": 5, "type": "Odd new"}`]]

but this is an invalid json data. my expected data is

    [{"id": 1, "type": "Even"}, {"id": 2, "type": "Odd"}, {"id": 3, "type": "Even"}, {"id": 4, "type": "Even new"}, {"id": 5, "type": "Odd new"}`]

what am i doing wrong.?

like image 466
Rashed Ehsan Avatar asked Oct 29 '22 22:10

Rashed Ehsan


1 Answers

Looks like your variable dict_data doesn't contain a single dict, but a list of dicts. You're .appending that list inside the outer list, thus generating a nested structure

If that is the case, then just use .extend to extend the original list with another list:

data.extend(dict_data)

Consider changing the name of the variable dict_data to something more meaningful, because it is confusing to read your code since it doesn't even hold a dict.

like image 179
nosklo Avatar answered Nov 11 '22 13:11

nosklo