Michael
Michael

Reputation: 179

Python - Add to json list via Python

My json file

{
   "people": []
}

My python code

with open("people.json") as jsonFile:
    load = json.load(jsonFile)
    data = {
    "fname": "Jason",
    "lname": "Scott",
    "age": 32,
    "job": "web developer",
    "spouse": "Jane Scott"
    }

    load["people"].append(data)

jsonFile.close()

I want to add to the list from my python file, with my code above, the json file remains unchanged.

Upvotes: 0

Views: 173

Answers (1)

TerryA
TerryA

Reputation: 59974

You haven't written anything back into the file. Open up the file in write mode (open("people.json", r+)), then after you append the data, you'll need to json.dump the new dictionary into the file.

Also, no need to do jsonFile.close() at the end. Your with statement deals with that.

Upvotes: 5

Related Questions