如何用jq在Bash中条件校验JSON数组内的指定兄弟对象键值对
使用jq检查产品JSON数组的双重条件
核心命令
直接返回布尔值(true/false):
jq 'any(.[]; .type == "barcode") and any(.[]; .type == "category" and .name == "food")'
如果需要更直观的文本输出:
jq 'if any(.[]; .type == "barcode") and any(.[]; .type == "category" and .name == "food") then "产品符合要求" else "产品不符合要求" end'
命令解释
any(.[]; .type == "barcode"):遍历数组中的每个对象,检查是否存在任意一个对象的type字段为barcodeany(.[]; .type == "category" and .name == "food"):遍历数组,检查是否存在任意一个对象同时满足type为category且name为foodand逻辑运算符确保两个条件必须同时成立,最终返回对应结果
示例用法
假设API返回的数据已保存到product.json文件中:
cat product.json | jq 'any(.[]; .type == "barcode") and any(.[]; .type == "category" and .name == "food")'
如果直接从API获取数据:
curl -s "https://your-api-url.com/products" | jq 'any(.[]; .type == "barcode") and any(.[]; .type == "category" and .name == "food")'
内容的提问来源于stack exchange,提问作者4r7if3x
相关产品推荐
相关产品推荐

