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

使用yq合并YAML文件时如何保留根结构并将默认对象合并到每个子对象中?

解决YAML合并后丢失root根结构的问题

你的问题出在原命令只返回了合并后的数组元素,没有把它们放回原来的root键下面。我们需要修改命令,让它原地更新第一个文件的root数组元素,然后输出完整的第一个文件结构,这样就能保留根节点了。

正确的yq命令

yq eval-all 'select(fileIndex == 0).root.[] *= select(fileIndex == 1).defaults | select(fileIndex == 0)' ./master.yaml ./update.yaml

命令解释

咱们拆解一下这个命令的作用:

  • select(fileIndex == 0):先选中第一个输入文件(也就是master.yaml)
  • .root.[] *= select(fileIndex == 1).defaults:遍历root数组里的每一个元素,把第二个文件(update.yaml)里的defaults内容原地合并进去(*=操作符会保留原元素的字段,同时添加新字段)
  • | select(fileIndex == 0):最后输出修改后的第一个文件,这样就完整保留了root根结构

执行结果验证

运行这个命令后,你会得到完全符合预期的输出:

root:
  - name: First
    some_value: One
    other_value: true
    one_more: Three
  - name: Second
    some_value: Two
    other_value: true
    one_more: Three

原命令的问题分析

你原来的命令(select(fileIndex == 0).root.[] *+ select(fileIndex == 1).defaults)只是把每个数组元素和defaults合并后直接输出,相当于把root数组的元素“拆出来”了,没有把它们放回root键的结构里,所以才丢失了根节点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:27:40