我有一个问题,关于如何从存储在数组中的路径访问python中的json(或字典)。
这里有一个例子来说明:
假设我们在tst.json文件中有这个json:
{
"firstName": "Jane",
"lastName": "Doe",
"hobbies": ["running", "sky diving", "singing"],
"age": 35,
"children": [
{
"firstName": "Alice",
"age": 6
},
{
"firstName": "Bob",
"age": 8
}
]
}
我将其加载到我的python程序中:
with open("tst.json", "r+") as read_file:
data = json.load(read_file)
现在我有以下数组(仅作为示例,但可以是任意数量的变量和深度)
tab_path = [["firstName"], ["children", "age"]]
tab_modif = ["Louve", 2]
我知道要访问tab_path中包含的路径,以便进行tab_modif中指示的修改。
例如,修改后的json将如下所示:
{
"firstName": "Louve",
"lastName": "Doe",
"hobbies": ["running", "sky diving", "singing"],
"age": 35,
"children": [
{
"firstName": "Alice",
"age": 2
},
{
"firstName": "Bob",
"age": 8
}
]
}
有没有一种方法可以从数组中快速构建路径,以便拥有
data['children']['age']
并将其修改为2
我希望我足够清楚!谢谢