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

如何使用jq根据JSON对象的name字段值获取对应KeyID

使用jq通过name字段匹配获取对应的KeyID

当然可以!用jq工具轻松就能实现根据name字段内容(包含指定字符串)提取对应KeyID的需求,下面我给你详细说明操作方法和示例:

你的源JSON数据

首先把你提供的JSON数据保存为input.json(或者直接通过管道传递):

{
  "201110131738QP27N": { "parent": 17, "name": "CentralServer", "status": "Active", "count": 6 },
  "201803271459ICV69": { "name": "subaccount1", "status": "Active", "count": 1 },
  "2018032715008ZM2G": { "name": "subaccount2", "status": "Active", "count": 1 },
  "201803281536PSKR4": { "name": "Este e um teste", "status": "Active" }
}

核心jq命令

1. 匹配包含指定字符串的name字段

如果你想查找**name字段包含"subacco"**的所有条目对应的KeyID,使用这条命令:

jq 'to_entries[] | select(.value.name | test("subacco")) | .key' input.json

执行后会输出:

"201803271459ICV69"
"2018032715008ZM2G"

命令拆解:

  • to_entries[]:将JSON对象转换为键值对数组(每个元素格式为{"key": "KeyID", "value": {...}})
  • select(.value.name | test("subacco")):筛选出value中的name字段匹配正则表达式subacco的条目(test()支持模糊匹配)
  • .key:提取筛选后条目的KeyID

2. 精确匹配name字段

如果需要精确匹配某个name值(比如查找name为"CentralServer"的KeyID),把test()换成==即可:

jq 'to_entries[] | select(.value.name == "CentralServer") | .key' input.json

输出结果:

"201110131738QP27N"

3. 动态传递匹配字符串(更灵活)

如果你不想每次修改命令里的匹配字符串,可以通过--arg参数传递变量:

SEARCH_STR="subacco"
jq --arg str "$SEARCH_STR" 'to_entries[] | select(.value.name | test($str)) | .key' input.json

这样只需修改SEARCH_STR的值就能匹配不同的内容,非常方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:13:07