我的 JSON 文件中有一个大树,我正在搜索用于从此 JSON 加载嵌套在嵌套键中的 python 语法。 假设我有这个:
{
"FireWall": {
"eth0": {
"INPUT": {
"PING": 1,
}
}
}
}
根据手册页和 Stackoverflow 中的一些问题,我尝试了这个(和一些变体):
import json
config = open('config.json', 'r')
data = json.load('config')
config.close()
if data['{"FireWall", {"eth0", {"INPUT", {"Ping"}}}}'] == 1:
print('This is working')
没有结果。执行此操作的正确方法是什么(尽可能简单)?谢谢!
最佳答案
您正在尝试 data = json.load('config')
加载字符串而不是文件对象,并且 data['{"FireWall", {"eth0", {"INPUT", {"Ping"}}}}']
这不是访问嵌套字典键值的正确方法。
import json
with open('config.json', 'r') as f:
data = json.load(f)
if data["FireWall"]["eth0"]["INPUT"]["Ping"] == 1:
print('This is working')
关于python - 用于加载嵌套在 JSON 文件的嵌套键中的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56754338/