如何用jq合并GitHub API返回的重复仓库文件列表?
使用jq合并GitHub代码搜索结果中的重复仓库文件列表
直接修改你的命令,替换原有jq逻辑即可实现合并:
gh api --method=GET "search/code?q=some-specific-string" | jq '[.items[] | {repo: .repository.full_name, path: .path}] | reduce .[] as $item ({}; .[$item.repo] += [$item.path]) | to_entries | map({(.key): .value})'
逻辑拆解:
格式化原始数据:
[.items[] | {repo: .repository.full_name, path: .path}]
将API返回的每个搜索结果项,转换为包含repo(仓库全名)和path(文件路径)的结构化对象数组,简化后续分组操作。分组合并文件路径:
reduce .[] as $item ({}; .[$item.repo] += [$item.path])
用reduce遍历数组,以仓库名为键构建累加对象:每遇到同一个仓库,就将对应的文件路径追加到该仓库的数组中,自动完成重复仓库的文件列表合并。转换为目标格式:
to_entries | map({(.key): .value})to_entries将上一步的对象转换为{key: "仓库名", value: ["文件路径"]}的条目数组;map再把每个条目转换为你需要的{"仓库名": ["文件路径"]}格式对象,最终输出目标数组结构。
输出示例:
[ { "org-name/helm-charts": [ "README.md" ] }, { "org-name/repo-name": [ "file-name-1.py", "file-name-2.py" ] } ]
内容的提问来源于stack exchange,提问作者Rumbles
相关产品推荐
相关产品推荐

