如何使用JQ过滤嵌套对象数组,仅保留指定字段?
JQ提取JSON指定字段:限制reviews数组的输出字段
需求说明
需要从给定的JSON数据中提取以下字段:
.title.url.author.login.reviews.author.login.reviews.state.mergedBy.login
已写出部分JQ语句,但不知道如何将reviews数组的字段限制为author.login和state:
map({ title: .title, URL: .url, author: .author.login, reviews: .reviews, "merged by": .mergedBy.login})
解决方案
对.reviews数组嵌套使用map()方法,遍历每个review对象并提取目标字段即可。修改后的完整JQ语句如下:
map({ title: .title, URL: .url, author: .author.login, reviews: .reviews | map({ author: .author.login, state: .state }), "merged by": .mergedBy.login })
输出示例
针对提供的JSON数据,执行上述语句后会得到精简后的结果:
[ { "title": "Jedi Training", "URL": "https://github.com/rebels/training/pull/222", "author": "luke123", "reviews": [ { "author": "han123", "state": "APPROVED" }, { "author": "leia", "state": "APPROVED" } ], "merged by": "luke123" } ]
内容的提问来源于stack exchange,提问作者David Williams
相关产品推荐
相关产品推荐

