我想在 python 中有一个方法来查找任何我知道名称的对象,在 json 的任何层次级别。
现在,我正在尝试查找并替换以下 json 中的对象的值:
{
"world": {
"soil": {
"obstacleDirectory": "obstacle",
"dimensions": {
"width": "100",
"length": "100",
"depth": "1",
"cellSize": "10"
},
我可以访问第一个类别,"world":
,或打印整个文件,但我无法使用以下命令在文件中找到对象"width":
for 循环:
filename = 'run_params.json'
with open(filename, 'r+') as f:
data = json.load(f)
for value in data.items():
print value
if "width" == data.keys():
print "width found!"
我根本无法在 json 文件中找到 "width"
对象。
对于我应该使用 python 中的哪种类型的函数来获取这样的方法,您有什么建议吗?
最佳答案
这是一个嵌套在字典中的字典,嵌套在字典中。您必须递归地展平字典,直到找到您要查找的内容。
import json
filename = 'run_params.json'
def flatten(d):
for k, v in d.items():
if isinstance(v, dict):
if 'width' in v.keys():
return v['width']
else:
return flatten(v)
with open(filename, 'r+') as f:
data = json.load(f)
found_it = flatten(data)
print(found_it)
关于python - 访问和替换 json 中的子类别对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56430837/