Grab top level json element with jq

46 views Asked by At

I can grab sub elements without an issue, but if i try top level element it fails, i was wondering if anyone knew the best way to grab the value for the ID element

This works to grab sub elements

AUTHENTICATOR_NAME=$(echo "$RESPONSE2" | jq '.[] | .profile.authenticatorName')
    

This does not work for grabbing the value of "id" at a higher level, it returns "jq: error (at :1): Cannot index array with string "id"

FACTOR_ID=$(echo "$RESPONSE2" | jq -r '.id')


    [
    {
        "id": "xxxxxxxxxxx1111111111",
        "factorType": "webauthn",
        "provider": "FIDO",
        "vendorName": "FIDO",
        "status": "ACTIVE",
        "created": "2024-01-31T19:38:50.000Z",
        "lastVerified": "2024-02-27T13:28:19.000Z",
        "lastUpdated": "2024-01-31T19:38:50.000Z",
        "profile": {
            "credentialId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            "appId": null,
            "version": null,
            "authenticatorName": "YubiKey 5",
            "presetPinAvailable": null,
            "fulfillmentProvider": null
1

There are 1 answers

2
Vivick On

The error is explicit: you're trying to use "id" to access an element of an array.

In the first case you use '.[] | .profile.authenticatorName' which is equivalent to "map each element of the array to its sub property '.profile.authenticatorName'"

In the second case you use '.id' which is "extract the 'id' property from the input".

What you probably meant to use is '.[] | .id' which is "map each element of the array to its property 'id'"