Home > database >  Rename incrementing JSON objects in python
Rename incrementing JSON objects in python

Time:05-22

I have a JSON file that looks like this:

"153689763780624385": {
    "1": {
        "author": "Mike",
        "date": "05/06/2022, 12:00:57"

    },
    "2": {
        "author": "Mike",
        "date": "05/06/2022, 13:29:43"

    },
    "3": {
        "author": "Jan01p",
        "date": "05/7/2022, 16:01:22"
    }
}

What I am doing is accessing my JSON, and deleting the 2nd object key in the json file. With the following code.

with open("pins.json", "r ") as f:
    p = json.load(f)
gid = "153689763780624385"
del p[gid]["2"]
with open("pins.json", "w ") as fp:
     json.dump(p, fp, indent=4)

Now my JSON looks like this

"153689763780624385": {
    "1": {
        "author": "Mike",
        "date": "05/06/2022, 12:00:57"

    }
    "3": {
        "author": "Jan01p",
        "date": "05/7/2022, 16:01:22"
    }
}

My goal here is to use a loop of some sort to rename all the following keys to be in order. So change 3 to 2. Name 4 to 3 and so on. The JSON is much larger just made it shorter for asking purposes. What's a good way to rename the keys to go in incrementing order? So far i'm thinking of dict.pop in a for loop. But can't figure it out.

CodePudding user response:

You can use the below logic to reorder all the keys.

my_dict1 = {"1": "a", "3": "b", "4": "c", "5": "d"}
my_dict2 = {str(i 1):v for i, v in enumerate(my_dict1.values())}

print(my_dict2)
# {'1': 'a', '2': 'b', '3': 'c', '4': 'd'}

This solution can only be used for Python version 3.7 and newer, as dictionaries before this version are unordered.

CodePudding user response:

Assuming your keys are all numbers as strings and you just want to rest them 1. Using the dict.pop() method:

value_to_remove = 2

with open("pins.json", "r ") as f:
    p = json.load(f)
gid = "153689763780624385"

del p[gid][str(value_to_remove)]

for key, values in p[gid].items():
    if int(key) > value_to_remove:
        p[gid][str(int(key)-1)] = p[gid].pop(str(key))

with open("pins.json", "w ") as fp:
     json.dump(p, fp, indent=4)

If the key value saved in gid is the only one you want to be removed the "2" key. Then it is ok. If you want to implement this for every 'first key', you can iterate over every first keys in the json dict.

  • Related