How to add item into a list stored in JSON file

Question:

I want to add a dictionary into a list that I have in my JSON file.

reading = []
reading["game_review"] = {
    "name" : your_name,
    "time" : round(time_result, 2),
    "level" : level+1
}

with open("stat.json", "a") as stats:
    json.dump(reading, stats)

Every time I run the code, another dictionary creates in the JSON file and puts itself next to the dictionary that I already have, I want it to add itself into a list inside a dictionary.

Edited:

with open("stat.json", "r") as stat_read:
    reading = json.loads(stat_read.read())

reading["game_review"] = {
    "name" : your_name,
    "time" : round(time_result, 2),
    "level" : level+1
}

with open("stat.json", "a") as stats:
    json.dump(reading, stats)
Asked By: Oliver Hnat

||

Answers:

If you want to do that, read that file, parse the JSON content then append the JSON in the list. then re-write the file.

suppose a JSON file has the following content

{"a": ["b", "c"], "d": "e"}

then you can do the following

with open("data.json") as jfile:
   current_data = json.load(jfile)

current_data['a'].append('f')

with open("data.json", "w") as jfile:
   json.dump(current_data, jfile)

the final content in the file will be

{"a": ["b", "c", "f"], "d": "e"}
Answered By: Atreyagaurav
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.