如何用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
相关产品推荐
相关产品推荐

