Python遍历JSON查找非readOnly键并打印对应值的方法
问题根因
原代码没有输出是两层遍历逻辑完全写错了:
- 第一层循环直接遍历
config字典,拿到的each_ctrlr是类似AlignedDataCtrlr的字符串键,不是对应的配置字典对象 - 第二层循环遍历这个字符串,拿到的是单个字符,根本不可能匹配到
readOnly字段,自然不会有任何输出 - 另外原代码中for循环前多了不必要的缩进,本身也不符合Python语法规范
正确实现代码
推荐用with上下文管理器读写文件,自动处理文件关闭逻辑,完整代码如下:
import json # 加载配置文件 with open("./configs/configuration.json", "r", encoding="utf-8") as file: config = json.load(file) # 逐层遍历配置 for controller_name, controller_conf in config.items(): # 跳过非字典类型的配置节点,兼容后续可能的扩展字段 if not isinstance(controller_conf, dict): continue # 遍历当前控制器下的所有配置项 for item_name, item_detail in controller_conf.items(): # 判断当前配置项是否包含readOnly字段,且值为False if isinstance(item_detail, dict) and item_detail.get("readOnly") == False: print(f"[{controller_name}] {item_name}: {item_detail}")
运行效果
针对你给出的示例配置,运行后会输出所有符合要求的配置项:
[AlignedDataCtrlr] Measurands: {'readOnly': False, 'value': []} [AlignedDataCtrlr] Interval: {'readOnly': False, 'value': 50, 'unit': 'seconds'} [AlignedDataCtrlr] TxEndedMeasurands: {'readOnly': False, 'value': []} [AuthCacheCtrlr] AuthCacheEnabled: {'readOnly': False, 'value': True}
如果只需要打印配置项的有效值,直接取item_detail.get("value")输出即可。
内容的提问来源于stack exchange,提问作者Humberto Adhemar
相关产品推荐
相关产品推荐

