I hope you all are doing well. I am having a problem with removing a dictionary from a json file:
I have a users.json which has data like this:
{
"0": {
"course": "fjjc",
"password": "fhjf",
"username": "1800101253"
},
"1": {
"course": "fjjc",
"password": "fhjf",
"username": "1800101254"
},
"2": {
"course": "fjjc",
"password": "fhjf",
"username": "1800101257"
},
"3": {
"course": "fjjc",
"password": "fhjf",
"username": "1800101258"
},
"Total": 4
}
I am trying to remove any key with all its nested data like for example "0" key and then arrange the json file in order which will have keys in this order "0","1","2","3" with their nested dictionary. So if "0" key is removed, the output should be like this:
{
"0": {
"course": "fjjc",
"password": "fhjf",
"username": "1800101254"
},
"1": {
"course": "fjjc",
"password": "fhjf",
"username": "1800101257"
},
"2": {
"course": "fjjc",
"password": "fhjf",
"username": "1800101258"
},
"Total": 3
}
Check that "1" key data came to "0" and similar for all. I am well aware that keys values doesn't change, but I do believe there is a solution for this problem. So help me out please :)
I was able to remove the "0" key with its nested dictionary, but was never able to implement the json with keys in sorted order like it was before.
My Test Code:
with open("users.json") as jsonFile3: #Reading users details into users.json
users = json.load(jsonFile3)
total = users["Total"]
for i in range(total):
if users[f"{i}"]["username"] == f"{username}":
del users[f"{i}"]
pos=i
removed = True
if removed == True:
for i in range(pos,total):
if f"{i}" in users:
if i==0:
continue
else:
users[f"{key-1}"] = users.pop(f"{key}")
users["Total"] = total-1
with open("users.json",'w') as jsonFile4:
json.dump(users,jsonFile4, indent=4, sort_keys=True)