Home > other >  Python List Comprehension to Delete Dict in List
Python List Comprehension to Delete Dict in List

Time:09-29

{
   "Credentials": [
      {
         "realName": "Jimmy John",
         "toolsOut": null,
         "username": "291R"
      },
      {
         "realName": "Grant Hanson",
         "toolsOut": null,
         "username": "98U9"
      },
      {
         "realName": "Gill French",
         "toolsOut": null,
         "username": "F114"
      }
   ]
}    

I have a json file formatted as above and I am trying to have a function delete an entry based on the username input from a user. I want the file to then be overwritten with the entry removed.

I have tried this:

 def removeUserFunc(SID):
            print(SID.get())
            with open('Credentials.json','r ') as json_file:
                data = json.load(json_file)
                data['Credentials'][:] = [item for item in data['Credentials'] if item['username'] != SID.get()]
                json_file.seek(0)
                json.dump(data,json_file,indent=3,sort_keys=True)

It partially works as everything in the Credentials section looks normal, but it appends a strange copied piece to the end that breaks the JSON. Say I was removing Grant and I ran this code, my JSON looks like below:

{
   "Credentials": [
      {
         "realName": "Marcus Koga",
         "toolsOut": null,
         "username": "291F"
      },
      {
         "realName": "Gill French",
         "toolsOut": null,
         "username": "F114"
      }
   ]
}        "realName": "Gill French",
         "toolsOut": null,
         "username": "F114"
      }
   ]
}

I am relatively new to Python and editing JSONs as well.

CodePudding user response:

You need to truncate the file after writing:

 def removeUserFunc(SID):
            print(SID.get())
            with open('Credentials.json','r ') as json_file:
                data = json.load(json_file)
                data['Credentials'][:] = [item for item in data['Credentials'] if item['username'] != SID.get()]
                json_file.seek(0)
                json.dump(data,json_file,indent=3,sort_keys=True)
                json_file.truncate()

CodePudding user response:

You can close the file and then open the file for writing-only, which will clear the the contents of the original file before writing the new contents.:

def removeUserFunc(SID):
    # open file for reading
    with open('Credentials.json','r') as json_file:
        # read the data to variable:
        data = json.load(json_file)

    # open file for writing:
    with open('Credentials.json','w') as json_file:
        data['Credentials'][:] = [item for item in data['Credentials'] if item['username'] != SID.get()]
        json.dump(data,json_file,indent=3,sort_keys=True)

CodePudding user response:

file.seek(0) just moves the file pointer but does not change the length of the file. So if you do not overwrite the entire contents of the file you will leave residual content. Use file.truncate() to set the file length to zero before writing.

json_file.seek(0)
json_file.truncate()  # set file length to zero
json.dump(data,json_file,indent=3,sort_keys=True)
  • Related