转换的数字分量
path
到整数。然后在调用函数时将下标添加到元素字符串中
from functools import reduce
import operator
json_test = {'request_version': 'v1.0',
'fields': [{'team': [{'name': 'Real Madrid', 'colour': 'white'}],
'location': {'type': 'Feature',
'geometry': {'type': 'Point',
'coordinates': [0, 53]}},
'query': {'filter': '2024/25'},
'player': 'Bellingham'}]}
def update_attribute(element, json, new_value):
*path, last = element.split('.')
path = [int(item) if item.isdigit() else item for item in path]
target = reduce(operator.getitem, path, json)
target[last] = new_value
return json
update_attribute('fields.0.player', json_test, 'Mbappe')
这并不完美,因为如果你有一个键是数字字符串的字典,它就不起作用了。