Python:递归函数更新动态生成的嵌套json键值
Python: Recursive function to update dynamically generated nested json key value
我正在尝试更新动态 json 键值。但是我无法完成递归函数。我的 JSON 结构是
x = {
"payload": {
"name": "kabilan",
"address": {
"country": "value_to_change"
}
}
}
在上面的 json 中,"value_to_change" 的路径是 ['payload']['address']['country'],我将其存储为 "payload.address.country" 在数据库中。
这个嵌套的 json 结构是动态创建的,但我也知道关键路径。请找到我编写的代码来更改它
y = "payload.address.country"
y1 = y.split('.')
for item in y1:
if item == y1[-1]:
x[item] = "india"
else:
x = x[item]
print(x)
此代码returns
"country":"india"
。但我希望输出为
{
"payload": {
"name": "kabilan",
"address": {
"country": "india"
}
}
}
我想我在这里缺少递归函数。但我对此感到困惑。请帮我解决这个问题。提前致谢
简单写一个函数:
def update_x_from_y(x, y):
y = y.split('.')
n = len(y)
for idx, item in enumerate(y):
if idx == n - 1:
x[item] = "india"
else:
x = x[item]
x = {
"payload": {
"name": "kabilan",
"address": {
"country": "value_to_change"
}
}
}
y = "payload.address.country"
update_x_from_y(x, y)
print(x)
选择更能代表它们所代表的变量名称。顺便说一下,x
是一个字典,而不是 JSON,后者是数据结构的字符串表示形式。
x = {
"payload": {
"name": "kabilan",
"address": {
"country": "value_to_change"
}
}
}
key_path = "payload.address.country"
d = x
keys = key_path.split('.')
last_key = keys.pop()
for key in keys:
d = d[key]
d[last_key] = "india"
print(x)
打印:
{'payload': {'name': 'kabilan', 'address': {'country': 'india'}}}
我正在尝试更新动态 json 键值。但是我无法完成递归函数。我的 JSON 结构是
x = {
"payload": {
"name": "kabilan",
"address": {
"country": "value_to_change"
}
}
}
在上面的 json 中,"value_to_change" 的路径是 ['payload']['address']['country'],我将其存储为 "payload.address.country" 在数据库中。
这个嵌套的 json 结构是动态创建的,但我也知道关键路径。请找到我编写的代码来更改它
y = "payload.address.country"
y1 = y.split('.')
for item in y1:
if item == y1[-1]:
x[item] = "india"
else:
x = x[item]
print(x)
此代码returns
"country":"india"
。但我希望输出为
{
"payload": {
"name": "kabilan",
"address": {
"country": "india"
}
}
}
我想我在这里缺少递归函数。但我对此感到困惑。请帮我解决这个问题。提前致谢
简单写一个函数:
def update_x_from_y(x, y):
y = y.split('.')
n = len(y)
for idx, item in enumerate(y):
if idx == n - 1:
x[item] = "india"
else:
x = x[item]
x = {
"payload": {
"name": "kabilan",
"address": {
"country": "value_to_change"
}
}
}
y = "payload.address.country"
update_x_from_y(x, y)
print(x)
选择更能代表它们所代表的变量名称。顺便说一下,x
是一个字典,而不是 JSON,后者是数据结构的字符串表示形式。
x = {
"payload": {
"name": "kabilan",
"address": {
"country": "value_to_change"
}
}
}
key_path = "payload.address.country"
d = x
keys = key_path.split('.')
last_key = keys.pop()
for key in keys:
d = d[key]
d[last_key] = "india"
print(x)
打印:
{'payload': {'name': 'kabilan', 'address': {'country': 'india'}}}