试图获取一个YAML文件中的所有路径。

问题描述 投票:1回答:1

我有一个输入YAML文件(test.yml),如下图。

# sample set of lines
foo:
  x: 12
  y: hello world
  ip_range['initial']: 1.2.3.4
  ip_range[]: tba
  array['first']: Cluster1

array2[]: bar

源文件中的一些键包含方括号(可能是空的)。

我想得到文件中所有路径的逐行列表,最好是像这样。

foo.x: 12
foo.y: hello world
foo.ip_range['initial']: 1.2.3.4
foo.ip_range[]: tba
foo.array['first']: Cluster1
array2[]: bar

我已经用了 薯条 图书馆和 yaml-paths CLI,但无法得到想要的输出。试试这个。

yaml-paths -m -s =foo -K test.yml

输出:

foo.x
foo.y
foo.ip_range\[\'initial\'\]
foo.ip_range\[\]
foo.array\[\'first\'\]

每条路径都在一行,但输出结果有所有的转义字符 ( \ )。修改调用以删除-m选项("expand matching parent nodes")可以解决这个问题,但输出的不是每行一条路径。

yaml-paths -s =foo -K test.yml

give:

foo: {"x": 12, "y": "hello world", "ip_range['initial']": "1.2.3.4", "ip_range[]": "tba", "array['first']": "Cluster1"}

有什么办法可以让每行都有一个路径条目,但没有转义字符?我想知道ruamel模块中是否有路径查询的功能?

yaml pyyaml ruamel.yaml
1个回答
0
投票

你的 "路径 "不过是在你的YAML文档中连接的字符串表示键(可能还有索引)的映射(可能还有序列)。

这可以通过一个递归函数从YAML加载的数据中简单地生成。

import sys
import ruamel.yaml

yaml_str = """\
# sample set of lines
foo:
  x: 12
  y: hello world
  ip_range['initial']: 1.2.3.4
  ip_range[]: tba
  array['first']: Cluster1

array2[]: bar
"""

def pathify(d, p=None, paths=None, joinchar='.'):
    if p is None:
        paths = {}
        pathify(d, "", paths, joinchar=joinchar)
        return paths
    pn = p
    if p != "":
        pn += '.'
    if isinstance(d, dict):
        for k in d:
            v = d[k]
            pathify(v, pn + k, paths, joinchar=joinchar)
    elif isinstance(d, list):
        for idx, e in enumerate(d):
            pathify(e, pn + str(idx), paths, joinchar=joinchar)
    else:
        paths[p] = d


yaml = ruamel.yaml.YAML(typ='safe')
paths = pathify(yaml.load(yaml_str))

for p, v in paths.items():
    print(f'{p} -> {v}')

这就得到了

foo.x -> 12
foo.y -> hello world
foo.ip_range['initial'] -> 1.2.3.4
foo.ip_range[] -> tba
foo.array['first'] -> Cluster1
array2[] -> bar
© www.soinside.com 2019 - 2024. All rights reserved.