Python appending new Lists to JSON file with loop

Viewed 26

I want to update a JSON file in a for loop

In the for loop I have following code:

with open('immodata.json', 'a') as file:
    json.dump([{'preis' : priceList, 'plz' : plzList, 'zimmer' : roomList, 'wohnflaeche' : sqrList} for priceList, plzList, roomList, sqrList in zip(priceList, plzList, roomList, sqrList)], file)

The problem is this is adding the new Data as sole Data instead of continuing the JSON.

What I get:

[{"preis": "1750000", "plz": "5222", "zimmer": "5.5", "wohnflaeche": "185"}][{"preis": "1750000", "plz": "5222", "zimmer": "5.5", "wohnflaeche": "185"}]

What I want:

[{"preis": "1750000", "plz": "5222", "zimmer": "5.5", "wohnflaeche": "185"}, {"preis": "1650000", "plz": "5222", "zimmer": "5.5", "wohnflaeche": "155"}

I assume I have to read out the file, add the new data to the list, and then append to the JSON File, but I did not find out how I would to this.

1 Answers

Alright, thanks to the comments below my question I was able to solve the problem.

json_data = []

#GET OLD LIST
if exists('immodata.json'):
    with open ('immodata.json') as json_file:
     json_data = json.load(json_file)
else:
    with open('immodata.json', 'a') as file:
        print("Created new immodata.json File")

#CREATE THE NEW LIST
new_list = [{'preis': priceList, 'plz': plzList, 'zimmer': roomList, 'wohnflaeche': sqrList} for priceList, plzList, roomList, sqrList in zip(priceList, plzList, roomList, sqrList)]

#ADD THE NEW LIST TO THE OLD
json_data += new_list


with open('immodata.json', 'w') as file:
    json.dump(json_data, file)

I downloaded the file, added the new list to the old one and then wrote this to a new one.

Related