You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅解析YAML文件指定key或限制解析器的遍历深度?

部分解析非全量合法YAML指定Key的解决方案

PyYAML官方没有提供直接传入keys参数的加载接口,但可以通过自定义SafeLoader的方式实现你要的效果,无需自行扫描匹配行,也支持限制遍历深度:

实现思路

重写YAML构造器的映射构建逻辑,仅在指定深度范围内匹配目标key,仅对命中的key执行内容解析,其余内容直接跳过,只要目标key对应的内容段合法即可正常提取,不受文件其他部分语法错误影响。

代码示例

1. 自定义目标Key加载器

import yaml
from yaml.reader import Reader
from yaml.scanner import Scanner
from yaml.parser import Parser
from yaml.composer import Composer
from yaml.constructor import SafeConstructor

class PartialTargetLoader(Reader, Scanner, Parser, Composer, SafeConstructor):
    def __init__(self, stream, target_keys=None, max_depth=1):
        # 初始化配置:要提取的目标key、最大解析深度
        self.target_keys = target_keys if target_keys is not None else []
        self.max_depth = max_depth
        self.current_depth = 0
        # 父类初始化
        Reader.__init__(self, stream)
        Scanner.__init__(self)
        Parser.__init__(self)
        Composer.__init__(self)
        SafeConstructor.__init__(self)
    
    def construct_mapping(self, node, deep=False):
        self.current_depth += 1
        mapping = {}
        # 仅在指定深度范围内解析目标key
        if self.current_depth <= self.max_depth:
            for key_node, value_node in node.value:
                key = self.construct_object(key_node, deep=deep)
                if key in self.target_keys:
                    # 仅对目标key的内容做完整解析
                    mapping[key] = self.construct_object(value_node, deep=True)
        self.current_depth -= 1
        return mapping

2. 调用方式

with open('maybe_valid.yaml', 'r', encoding='utf-8') as f:
    # 示例:仅解析顶层的hosts key
    conf = yaml.load(
        f, 
        Loader=lambda s: PartialTargetLoader(s, target_keys=['hosts'], max_depth=1)
    )

# 输出提取到的hosts内容
print(conf.get('hosts'))

参数说明

  • target_keys:要提取的key列表,支持同时指定多个目标key
  • max_depth:最大解析深度,设为1时仅检查顶层节点,设为2时检查顶层和下一层节点,以此类推

这个实现无需手动处理文件行匹配,也不会因为文件其他部分的YAML语法错误导致解析失败,完全匹配需求。


内容的提问来源于stack exchange,提问作者Gree Tree Python

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 17:54:03