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

如何使用yq通过匹配另一映射的键值筛选列表元素?

YQ 查询匹配问题解答

原始YAML数据:

example_a:
  - key: sa01
    name: sa

match_a:
  sa_key: sa01

以下命令可以正常运行,能筛选出example_a中key为sa01的条目:

yq '.example_a[] |select(.key == "sa01")' 

问题:是否可以通过以下命令实现相同功能?

yq '.example_a[] |select(.key == .match_a.sa_key)'

不行,因为执行到select阶段时,当前上下文(.)已经指向example_a数组里的单个元素了,没法直接访问顶层的match_a节点。要实现相同效果,可以用两种方式:

  1. 先把顶层的match_a.sa_key存为变量,再在筛选时引用:
yq '($match := .match_a.sa_key) | .example_a[] | select(.key == $match)'
  1. 使用相对路径访问顶层节点:
yq '.example_a[] | select(.key == ../match_a.sa_key)'

内容的提问来源于stack exchange,提问作者naxoki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:55:24