Using jq to select value from multiple datatypes (array/object)

Viewed 81

I have a curl cmd and return either one of json structure as below

#1

{
    "keys": [
      {
        "key": "1234567890"
      }
    ]
}

#2

{
    "keys": [
      "1234567890"
    ]
}

Shell/bash script (Mac)

key=$(curl "blah blah blah" | jq '??????')

what would be ????? look like to get the key by either one of json structure

billion thanks

3 Answers

One way would be to do an explicit check of the type of the content within keys as

.keys[] | if type == "string" then . elif type == "object" then .key else empty end

jqplay demo

Just to add a further alternative as a mixture of the conciseness of @pmf's solution and the readability of @inian's solution (both great approaches):

.[].keys|first|(.key? // .)  
Related