python - 用于加载嵌套在 JSON 文件的嵌套键中的语法

标签 python json

我的 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/

相关文章:

python - 如何在Python中检查两个列表是否循环相同

java - Jersey/JAX-RS 客户端抛出 400 错误请求

json - Cakephp - 如果请求是 JSON?

javascript - 将监听器添加到 firebase 生成的 key 内的子级?

java - 具有完整 POJO 数据绑定(bind)的 Jackson 自定义过滤器

android - "IllegalStateException: Content has been consumed"

python - 针对 Windows 计算机使用 impacket 的 SMB 客户端时“无法请求 session ”

python - 并行化 np.searchsorted

python - 如何在 Mac 终端查看 Python 命令的整个历史记录

python - python中的离散优化