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

如何使用yq筛选后聚合映射,生成指定格式的JSON结果?

解决yq聚合嵌套键值对为单个JSON对象的问题

正确命令1(使用reduce遍历聚合)

yq -o=json e 'reduce .paths[][] as $item ({}; if $item.x-required-scopes != null then .[$item.operationId] = $item.x-required-scopes else . end)' test-spec.yaml

正确命令2(先过滤再合并数组)

yq -o=json e '[.paths[][] | select(.x-required-scopes != null) | {.operationId: .x-required-scopes}] | add' test-spec.yaml

命令说明

  • 第一种方法通过reduce遍历所有路径下的操作对象,以空对象为初始值,仅将包含x-required-scopes的项,以operationId为键、x-required-scopes为值添加到结果对象中。
  • 第二种方法先筛选出存在x-required-scopes的项,将它们转为单个键值对的对象并存入数组,最后用add把数组内的所有对象合并成一个完整的JSON对象。

验证输出

执行上述任意命令后,会得到期望的结果:

{
  "AdminPing": [
    "test-scope"
  ],
  "DeleteUser": [
    "test-scope",
    "users:write"
  ]
}

之前尝试的问题分析

  • 命令1输出多个独立对象:直接遍历输出每个对象,缺少聚合操作,导致结果分散。
  • 命令2输出对象数组:虽然将对象存入数组,但未使用add将数组内的对象合并为单个对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:01:20