Im trying to delete a single index in a list which is inside a json file
the file
{
"0": [
"0",
"1",
"2",
"3"
]
}
The program
import json
with open("main.json","r") as jsonfile:
jsonfile = json.load(jsonfile)
key = "0"
index = int(input("which index u want to remove: "))
with open("main.json","r ") as f:
if key in jsonfile:
#jsonfile[key].append(str(index))
del jsonfile[key][index]
json.dump(jsonfile,f,indent=3)
This is how it looks after the programme deletes the index:
Please say how to stop this problem. Im using repl.it
CodePudding user response:
The problem is with saving your file. Firstly, use "w"
not "r "
because you are not reading. Secondly, to save it, simply use:
f.write(json.dumps(jsonfile))
See: Delete an element in a JSON object
CodePudding user response:
Change to "r " to "w" to write the whole file again.
with open("main.json","w") as f:
if key in jsonfile:
#jsonfile[key].append(str(index))
del jsonfile[key][index]
json.dump(jsonfile,f,indent=3)
CodePudding user response:
The error is with the "r " which should be "w":
import json
with open("main.json","r") as jsonfile:
jsonfile = json.load(jsonfile)
key = "0"
index = int(input("which index u want to remove: "))
with open("main.json","w") as f:
if key in jsonfile:
#jsonfile[key].append(str(index))
del jsonfile[key][index]
json.dump(jsonfile,f,indent=3)
Works on replit.com, I know because thats what I use.