jsonjwtjq

How to filter only the object name using jq/jmespath?


I have the following 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

}

With jq, I can easily filter keys like:

$ jq -r '.httpsOnly'
true

or

$ jq -r '.identity.principalId
null

and retrieve their respective values, so that I could use them in a shell script as variables.

Question is: how to filter the identity.userAssignedIdentities object to obtain only the <random_object_name> name/content, like so:

$ jq -r '.identity.userAssignedIdentities.???'
<random_object_name>

but not the remaining key-value pairs?


Solution

  • If there is only one key, you can use the first item of the array provided by keys:

    jq -r '.identity.userAssignedIdentities | keys[0]'
    

    Demo

    If there is more than one, use [] instead of [0] to iterate over all keys, which will also be sorted. Use keys_unsorted[] for an unsorted list.