You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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字段为barcode
  • any(.[]; .type == "category" and .name == "food"):遍历数组,检查是否存在任意一个对象同时满足type为category且name为food
  • and逻辑运算符确保两个条件必须同时成立,最终返回对应结果

示例用法

假设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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:55:24