I need to change values of items "Id" "SummaryId" and "CoworkersId" in my json. I have already code which will change values of "Id" and "SummaryId"
. Code below generates new unique Id for these 2 items. I need that this code will change "CoworkersId" as well. As you can see the same value is in these 3 items – a4555752s. The issue is that item "CoworkersId" is a list, not a string and contain 2 elements.
import json
import random
class Cache:
# A dictionary that keeps a record of "seen" keys
key_cache = {}
@classmethod
def generate_replacement_key(cls, key: str) -> str:
"""
If key has already been seen, then return the cached key for that,
otherwise generate and store a new key.
"""
new_key = cls.key_cache.setdefault(key, cls.generate_random_key())
return new_key
@classmethod
def generate_random_key(cls) -> str:
"""
returns a random key, that hasn't been generated before
"""
new_key = str(random.randint(1000, 1000000))
if new_key in cls.key_cache.values():
return cls.generate_random_key()
return new_key
a = '''
{
"people": [
{
"Name": "Jan",
"Lastname": "Szewc",
"Id": "a4555752s"
},
{
"Name": "Marek",
"Lastname": "Piorun",
"Id": "a4asa85",
"SummaryId": "a4555752s"
},
{
"Name": "Mikolaj",
"Lastname": "Ciekasz",
"Id": "a4ddd244",
"ManagerId": "a4555752s",
"CoworkersId":
[ "1278978",
"a4555752s"]
}
]}
'''
data = json.loads(a)
for people in data["people"]:
# use walrus operator to make less boilerplate-code.
if (id_string := people.get("Id")): # use dict.get to avoid key-errors.
people["Id"] = Cache.generate_replacement_key(id_string)
if (summary_id_string := people.get("SummaryId")):
people["SummaryId"] = Cache.generate_replacement_key(summary_id_string)
print(json.dumps(data, indent=2))
I need that values of all 3 elements "Id"
, "SummaryId"
and "CoworkersId"
will be changed.
2
Answers
I think I got it, but there must be more efficient method, this is just a quick thing.
SummeryId and Id of the first object are the same because in json that you supplied they are the same, this means that:
will return the same value since it already exists in the dict.
Output
You can loop through all the coworker ids to modify them, like this: