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

如何用jq/jmespath仅提取userAssignedIdentities中的对象名称?

问题

给定如下JSON结构:

{
"hostNamesDisabled": false,
"hostingEnvironmentProfile": null,
"httpsOnly": true,
"hyperV": false,
"identity": {
    "principalId": null,
    "tenantId": null,
    "type": "UserAssigned",
    "userAssignedIdentities": {
        "<random_object_name>": {
            "clientId": "xxxx",
            "principalId": "xxxx"
        }
    }
},
"inProgressOperationId": null,
"isDefaultContainer": null
}

已能通过jq提取普通键值对(如jq -r '.httpsOnly'返回true),现在需要提取identity.userAssignedIdentities下的键名(即<random_object_name>),而非其内部的键值对,求对应的jq和JMESPath写法。

解决方案

jq写法

要提取对象的键名,可使用keys或keys_unsorted(后者保留键的原始顺序)命令:

  • 提取单个键名(假设对象只有一个键):
    jq -r '.identity.userAssignedIdentities | keys[0]'
    
    执行后直接返回目标键名<random_object_name>
  • 如果对象有多个键,输出所有键名(每行一个):
    jq -r '.identity.userAssignedIdentities | keys[]'
    

JMESPath写法

使用keys()函数提取键名:

  • 提取单个键名:
    jp -r 'identity.userAssignedIdentities | keys(@)[0]'
    
  • 提取所有键名(每行一个):
    jp -r 'identity.userAssignedIdentities | keys(@)[]'
    

注:JMESPath工具通常用jp或jmespath-terminal执行,具体取决于你的安装方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 13:08:16