英文:
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:
- "5000:5000"
- "337:337"
pinger:
build:
I can read in the services to a bash array like so:
readarray -t services <<< $(yq e '.services | keys | .[]' example.yaml)
But when I try the case where the key has no sub-keys, I get an error:
yq e '.test | keys | .[]' 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 '.test | select(.) | keys | .[]' 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 '.test | select(.) | keys | .[]' example.yaml
yq e '.services | select(.) | keys | .[]' example.yaml
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论