使用jq移除JSON查询结果中services为空的条目,正确语法是什么?
jq过滤services为空条目的解决方案
你只需在原有jq表达式的末尾追加select(.services | length > 0),即可过滤掉services数组为空的无效条目。
完整正确命令
cat data.json | jq '.[] | {profile: .profile, services: [.clusters[].services[]| select(.taskdef[] | .name=="app" and .version=="1.3.2") | .taskdef[] ]} | select(.services | length > 0)'
逻辑说明
- 原有表达式会为每个profile生成包含
profile、services两个字段的独立对象 - 追加的
select语句作用于生成的每个对象,仅保留services数组长度大于0的结果,空数组的对象会被直接丢弃
执行后输出结果
{ "profile": "test1", "services": [ { "name": "app", "version": "1.3.2" } ] }
内容的提问来源于stack exchange,提问作者Tim Schill
相关产品推荐
相关产品推荐

