0

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: the

Please say how to stop this problem. Im using repl.it

DevER-M
  • 43
  • 9
  • `r+` does not truncate the file. You have been overwriting the beginning but the end is left in the file. – Klaus D. Nov 16 '21 at 06:49

3 Answers3

3

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

Larry the Llama
  • 958
  • 3
  • 13
3

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)
alphaBetaGamma
  • 653
  • 6
  • 19
-1

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.

Larry the Llama
  • 958
  • 3
  • 13
Agent Biscutt
  • 712
  • 4
  • 17