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

如何使用jq通过正则匹配displayName筛选JSON对象?

解决方法

你当前用的select(.displayName=="foo*")是精确匹配字符串"foo*",jq不会把*当成通配符解析,所以拿不到结果。要筛选所有displayName包含foo的对象,推荐两种实用方式:

方式1:用contains()函数做子串匹配

这个方法最简单,直接检查字符串是否包含指定子串:

cat /tmp/z.json | jq '.[] | select(.displayName contains "foo")'

执行后会输出符合条件的对象:

{
  "id": "1",
  "agent": "23ef",
  "displayName": "foo.com"
}
{
  "id": "2",
  "agent": "23gh",
  "displayName": "foo2.com"
}

方式2:用test()函数做正则匹配

如果需要更灵活的匹配规则(比如只匹配以foo开头的字符串、区分大小写等),可以用正则表达式:

  • 匹配以foo开头的内容(对应你原本想实现的foo*效果):
cat /tmp/z.json | jq '.[] | select(.displayName test "^foo")'
  • 匹配任意位置包含foo的内容:
cat /tmp/z.json | jq '.[] | select(.displayName test "foo")'

内容的提问来源于stack exchange,提问作者HariG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:13:12