Add new data to json file in python

I have a json array in data.json file

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

and I tried to add 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 get 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 invalid json data. my expected data

    [{"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.?

+4
source share
2 answers

try using

data.extend(dict_data)

extend() function actually extends your existing json data, on the other hand

append() function adds new data that you provide

+2
source

, dict_data dict, list of dict s. .append ing, list list,

, .extend list list:

data.extend(dict_data)

dict_data - , , dict.

+1

Source: https://habr.com/ru/post/1690077/


All Articles