如何使用JQ筛选name为Atlas的条目并仅显示其Id?
解决JQ提取指定name对应id的问题
我看你现在的JQ语句已经很接近正确结果了,只是语法上有个小细节没处理对~
原命令的问题
你当前的命令:
echo "${json}" |jq '.[] | select(.name=="atlas" | .id)'
错误在于把.id放到了select()的条件里,select()只需要传入判断条件(这里是.name == "atlas"),不需要在里面提取字段。
正确的写法
有两种常用的正确写法可以实现你的需求:
- 先筛选出符合条件的对象,再提取
id字段:
echo "${json}" | jq '.[] | select(.name == "atlas") | .id'
- 更紧凑的写法,直接在筛选后取
id:
echo "${json}" | jq '.[] | select(.name == "atlas").id'
测试验证
用你提供的JSON数据:
[ { "name": "atlas", "id": 2314430, "slug": "atlas", "description": "", "privacy": "closed", "url": "https://api.github.com/teams/2314430", "members_url": "https://api.github.com/teams/2314430/members{/member}", "repositories_url": "https://api.github.com/teams/2314430/repos", "permission": "pull" }, { "name": "HAL", "id": 2318635, "slug": "hal", "description": "", "privacy": "closed", "url": "https://api.github.com/teams/2318635", "members_url": "https://api.github.com/teams/2318635/members{/member}", "repositories_url": "https://api.github.com/teams/2318635/repos", "permission": "pull" } ]
执行正确命令后,会输出:
2314430
内容的提问来源于stack exchange,提问作者ehime
相关产品推荐
相关产品推荐

