英文:
How to change 'data' of all the values in key-value pair in JSON?
问题
以下是您要求的 JSON 数据更改后的部分:
[
{
"degree": "5pcBBS07",
"school": "ZozkeyAV",
"joinedOn": {
"year": "XYZ",
"month": "ABC"
},
"address": [
{
"b_Address": "ABC",
"city": "DEF"
},
{
"b_Address": "GHI",
"city": "JKL"
}
],
"fieldOfStudy": "MBA",
"levelOfEducation": "MASTER",
"currentlyStudying": "true"
}
]
这里,"degree"、"school"、"joinedOn" 和 "address" 的值已经更改为您所期望的格式。 "joinedOn" 和 "address" 现在都包含对象,而不仅仅是字符串。
您的代码看起来已经可以成功更改键的值,但如果您希望某些键的值是对象而不仅仅是字符串,您需要相应地修改 anonymize_json_data
函数以便它能够处理这些情况。在函数中,您需要检查字段的值是否已经是对象,如果是对象,则继续递归处理对象的内部字段。
这是一个示例修改的 anonymize_json_data
函数:
def anonymize_json_data(data, fields_to_anonymize):
for field in fields_to_anonymize:
if field in data:
if isinstance(data[field], dict):
# If the field is a dictionary, recursively anonymize its contents
anonymize_json_data(data[field], fields_to_anonymize)
elif isinstance(data[field], list):
# If the field is a list, iterate through its elements and anonymize each one
for item in data[field]:
anonymize_json_data(item, fields_to_anonymize)
else:
# Otherwise, generate a random string for the field
data[field] = generate_random_string()
return data
这个修改后的函数可以处理嵌套对象和列表,以便您可以获得期望的输出。
英文:
I have a JSON data which is:
json_string = '[
{
"degree": "masters",
"school": "PU",
"joinedOn": {
"year": 2021,
"month": "FEB"
},
"address": [
{
"b_Address": "UK",
"city": "London"
},
{
"b_Address": "US",
"city": "Texas"
}
],
"fieldOfStudy": "MBA",
"levelOfEducation": "MASTER",
"currentlyStudying": "true"
}
]'
I want to change the data of every keys like this:
{
"degree": "5pcBBS07",
"school": "ZozkeyAV",
"joinedOn": "y5cO3L9i",
"address": "mBa3oqMs",
"fieldOfStudy": "MBA",
"levelOfEducation": "MASTER",
"currentlyStudying": "true"
}
Here the values of "degree", "school","phone","joinedOn","address"
has been changed. Buy my expectation was since "joinedOn"
has an object
but the output is coming as:
"joinedOn": "y5cO3L9i"
I want the output to be:
"joinedOn": {
"year": XYZ,
"month": "ABC"
}
Same case goes for "address"
. I am just getting single value "mBa3oqMs"
, I want the output to be:
"address": [
{
"b_Address": "ABC",
"city": "DEF"
},
{
"b_Address": "GHI",
"city": "JKL"
}
]
I tired as:
json_string = '[{"degree": "masters", "school": "PU", "joinedOn": {"year": 2021, "month": "FEB"}, "address": [{"b_Address": "UK", "city": "London"},{"b_Address": "US", "city": "Texas"}], "fieldOfStudy": "MBA","levelOfEducation": "MASTER","currentlyStudying": "true"}]'
data = load_json_data(json_string)
if data:
fields_to_anonymize = ["degree", "school","phone","joinedOn","address"]
anonymized_data = anonymize_json_data(data[0], fields_to_anonymize)
# Alternatively, convert it back to a string
anonymized_json_string = json.dumps(anonymized_data)
print(anonymized_json_string)
Loading JSON file:
def load_json_data(json_string):
try:
data = json.loads(json_string)
return data
except json.JSONDecodeError as e:
print("Error parsing JSON:", str(e))
return None
Changing the values:
def anonymize_json_data(data, fields_to_anonymize):
for field in fields_to_anonymize:
if field in data:
data[field] = generate_random_string()
return data
def generate_random_string(length=8):
letters_and_digits = string.ascii_letters + string.digits
return ''.join(random.choice(letters_and_digits) for _ in range(length))
How can I get the output where key will have object and the object will have their own changed data?
答案1
得分: 1
你的代码无法正常工作,因为你忽略了字典中的某些值可能是dict
或list
类型。
你应该修改你的代码来处理这种情况,请查看下面带有所需更改的代码:
def randomize(data):
if isinstance(data, dict):
return {key: generate_random_string() for key, value in data.items()}
elif isinstance(data, list):
return [randomize(x) for x in data]
return data
def anonymize_json_data(data, fields_to_anonymize):
for key, value in data.items():
if isinstance(value, (dict, list)) and key in fields_to_anonymize:
data[key] = randomize(value)
elif key in fields_to_anonymize:
data[key] = generate_random_string()
return data
使用这些更改,你将能够以预期的格式获得输出。
输出:
{"degree": "85SovY6B",
"school": "D6YBpJDB",
"joinedOn": {"year": "ggbmvYEd", "month": "ZUoJOO6A"},
"address": [{"b_Address": "F6w5Qwsh", "city": "Xnz1pDbg"},
{"b_Address": "1zjZ0mLw", "city": "ofB677lP"}],
"fieldOfStudy": "MBA",
"levelOfEducation": "MASTER",
"currentlyStudying": "true"}
英文:
Your code is not working because you are ignoring the fact that some values of the dictionary can be of type dict
or list
You should change your code to handle that, Check the below code with the required changes
def randomize(data):
if isinstance(data, dict):
return {key: generate_random_string() for key, value in data.items()}
elif isinstance(data, list):
return [randomize(x) for x in data]
return data
def anonymize_json_data(data, fields_to_anonymize):
for key, value in data.items():
if isinstance(value, (dict, list)) and key in fields_to_anonymize:
data[key] = randomize(value)
elif key in fields_to_anonymize:
data[key] = generate_random_string()
return data
With this change you will be able to get the output in the expected format
Output:
{'degree': '85SovY6B',
'school': 'D6YBpJDB',
'joinedOn': {'year': 'ggbmvYEd', 'month': 'ZUoJOO6A'},
'address': [{'b_Address': 'F6w5Qwsh', 'city': 'Xnz1pDbg'},
{'b_Address': '1zjZ0mLw', 'city': 'ofB677lP'}],
'fieldOfStudy': 'MBA',
'levelOfEducation': 'MASTER',
'currentlyStudying': 'true'}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论