I would like to replace ID’s which for now contain numbers and letters with unique ID which contains only numbers.
Id’s now:
"Id": "a4555752s"
"SummaryId": "a4555752s"
"Id": "a4asa85"
"Id": "a4ddd244"
Second thing is that ID can be repeated in case if there are other items which belong to it and that would have to be changed together with specific ID if this is exact the same value like here.
"Id": "a4555752s"
"SummaryId": "a4555752s"
I wrote some code, but this is not very efficient since it is replacing all id’s with one unique id.
Code:
import json
import random
number = random.randint(1000,1000000)
a = '''
{
"people": [
{
"Name": "Jan",
"Lastname": "Szewc",
"Id": "174167"
},
{
"Name": "Marek",
"Lastname": "Piorun",
"Id": "764120"
},
{
"Name": "Mikolaj",
"Lastname": "Ciekasz",
"Id": "43409",
"ManagerId": "a4555752s",
"CoworkersId": [
"1278978",
"a4555752s"
]
}
]
}
'''
data = json.loads(a)
i = 0
for item in (data["people"]):
item["Id"] = item["Id"].replace(item["Id"], str(number))
print(data["people"])
results:
[{'Name': 'Jan', 'Lastname': 'Szewc', 'Id': '853251'}, {'Name': 'Marek', 'Lastname': 'Piorun', 'Id': '853251'}, {'Name': 'Mikolaj', 'Lastname': 'Ciekasz', 'Id': '853251', 'SummaryId': 'a4555752s'}]
Can you give me some tips?
3
Answers
You need to use generate the random number in the loop, and don’t use
str.replace
when replacing the whole value, just erase itin your case you havesometimes a key : SummaryId with this cod we can change both of them in that key exist and also you need this random number be a string right ?
If I understand you correctly, you want to cache generated keys, so that if they are referred to later in the iterations, you can use the same
Id
to refer to another object.There are built-in versions of caches, such as
functools.cache
. However, this is how I would solve the problem without using that decorator:And a sample output: