JavaScript
x
20
20
1
{
2
"Credentials": [
3
{
4
"realName": "Jimmy John",
5
"toolsOut": null,
6
"username": "291R"
7
},
8
{
9
"realName": "Grant Hanson",
10
"toolsOut": null,
11
"username": "98U9"
12
},
13
{
14
"realName": "Gill French",
15
"toolsOut": null,
16
"username": "F114"
17
}
18
]
19
}
20
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:
JavaScript
1
8
1
def removeUserFunc(SID):
2
print(SID.get())
3
with open('Credentials.json','r+') as json_file:
4
data = json.load(json_file)
5
data['Credentials'][:] = [item for item in data['Credentials'] if item['username'] != SID.get()]
6
json_file.seek(0)
7
json.dump(data,json_file,indent=3,sort_keys=True)
8
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:
JavaScript
1
20
20
1
{
2
"Credentials": [
3
{
4
"realName": "Marcus Koga",
5
"toolsOut": null,
6
"username": "291F"
7
},
8
{
9
"realName": "Gill French",
10
"toolsOut": null,
11
"username": "F114"
12
}
13
]
14
} "realName": "Gill French",
15
"toolsOut": null,
16
"username": "F114"
17
}
18
]
19
}
20
I am relatively new to Python and editing JSONs as well.
Advertisement
Answer
You need to truncate the file after writing:
JavaScript
1
9
1
def removeUserFunc(SID):
2
print(SID.get())
3
with open('Credentials.json','r+') as json_file:
4
data = json.load(json_file)
5
data['Credentials'][:] = [item for item in data['Credentials'] if item['username'] != SID.get()]
6
json_file.seek(0)
7
json.dump(data,json_file,indent=3,sort_keys=True)
8
json_file.truncate()
9