从YAML中使用yq读取键时,过滤掉空值情况。

huangapple go评论157阅读模式
英文:

Filter null case when reading in keys from YAML with yq

问题

我可以翻译代码部分和相关的问题,不包括要翻译的内容。以下是代码和问题的翻译:

Say I have a yaml file, `example.yaml`:

    test:
    services:
      registry:
        image: registry:2
        ports:
          - "5000:5000"
          - "337:337"
      pinger:
        build:

我可以将services读入一个bash数组,如下所示:

    readarray -t services  <<< $(yq e '.services | keys | .[]' example.yaml)

但是,当我尝试键没有子键的情况时,我会收到错误消息:

    yq e '.test | keys | .[]' example.yaml
    Error: Cannot get keys of !!null, keys only works for maps and arrays

有没有一种很好的方法来替换空值的情况并存储为假值?最终,我希望`test`存储为bash变量(== false)。
英文:

Say I have a yaml file, example.yaml:

test:
services:
  registry:
    image: registry:2
    ports:
      - &quot;5000:5000&quot;
      - &quot;337:337&quot;
  pinger:
    build:

I can read in the services to a bash array like so:

readarray -t services  &lt;&lt;&lt; $(yq e &#39;.services | keys | .[]&#39; example.yaml)

But when I try the case where the key has no sub-keys, I get an error:

yq e &#39;.test | keys | .[]&#39; example.yaml
Error: Cannot get keys of !!null, keys only works for maps and arrays

What is a good way of replacing the null case with a falsey value? Ultimately I'd like test to be stored as a bash variable ( == false).

答案1

得分: 1

使用select()函数与not运算符结合在应用keys函数之前过滤掉空值,就像这样:

yq e '.test | select(.) | keys | .[]' example.yaml

select(.)表达式将返回test键中的所有非空值。您也可以对其他键使用相同的方法:

yq e '.test | select(.) | keys | .[]' example.yaml
yq e '.services | select(.) | keys | .[]' example.yaml
英文:

Use the select() function in combination with the not operator to filter out the null values before applying the keys function like this;

yq e &#39;.test | select(.) | keys | .[]&#39; example.yaml

The select(.) expression will return all non-null values in the test key. You can use the same approach for those keys as well:

yq e &#39;.test | select(.) | keys | .[]&#39; example.yaml
yq e &#39;.services | select(.) | keys | .[]&#39; example.yaml

huangapple
  • 本文由 发表于 2023年3月8日 17:51:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定