2

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)
Amsal Khan
  • 33
  • 4
  • Would [this](https://stackoverflow.com/questions/10844064/items-in-json-object-are-out-of-order-using-json-dumps) solve your problem? – fsimonjetz Jun 04 '21 at 21:17
  • Thanks @fsimonjetz for trying to help but no that post only shows how to arrange data in a specific order which isn't something I am trying to achieve here. I already looked all types of forums and questions available on the internet and when didn't found any solutions, then I asked it in StackOverflow :D – Amsal Khan Jun 04 '21 at 21:53

1 Answers1

2

You can temporarily convert the dictionary to list, remove the item at specific index and create dictionary again in correct order. For example:

dct = {
    "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,
}

to_remove = 0

lst = [dct[str(v)] for v in range(dct["Total"])]
lst.pop(to_remove)
dct = {str(i): v for i, v in enumerate(lst)}
dct["Total"] = len(lst)

print(dct)

Prints:

{'0': {'course': 'fjjc', 'password': 'fhjf', 'username': '1800101254'}, 
 '1': {'course': 'fjjc', 'password': 'fhjf', 'username': '1800101257'}, 
 '2': {'course': 'fjjc', 'password': 'fhjf', 'username': '1800101258'},  
 'Total': 3}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Thanks a lot for helping out and giving such a fast response. This did the job what I was asking, spent nearly 5hours to figure out but never thought to use list lol. Now I want to extend it further to take more scenarios like suppose if there are two keys with nested dictionaries which has 'username' key's value same, then I want them both deleted and then the json arranged. I tried to implement this myself through saving positions and then running for loops but as pop changes the index once it pop out from list, it didn't worked out for me. If possible, could you help? – Amsal Khan Jun 04 '21 at 22:29
  • 1
    @AmsalKhan To not clutter the comment section, I'd suggest to open a new question here on StackOverflow. I'll try to look at it. – Andrej Kesely Jun 04 '21 at 22:30
  • Thanks for such a fast response Andrej. I appreciate your help! Anyways, I made a solution using while loop and running again and again, maybe not the best solution according to performance, but does the job for me. Anyways here the post if you have some better solution to add: https://stackoverflow.com/questions/67844859/remove-multiple-keys-and-values-with-its-nested-dictionary-then-arrange-keys-in – Amsal Khan Jun 04 '21 at 23:04