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.?
Looks like your variable dict_data
doesn't contain a single dict
, but a list
of dict
s. You're .append
ing 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With