sort_by on array elements gives error 'Cannot index string with string "key"'

AK1*_*123 7 sorting json jq

I'm trying to get the status of a code scan by the pull request ID and I'm having trouble getting the value of the status. The json file looks similar to below.

{
"pullRequests": [
{
  "key": "11346",
  "title": "feature/XXX-Validation",
  "branch": "feature/XXX-Validation",
  "base": "develop",
  "status": {
    "qualityGateStatus": "OK",
    "bugs": 0,
    "vulnerabilities": 0,
    "codeSmells": 1
  },
  "analysisDate": "2020-07-27T14:22:36+0000",
  "url": "https://abc/org/_git/repo/pullrequest/11346",
  "target": "develop"
},
{
  "key": "11151",
  "title": "feature/xxx-data",
  "branch": "feature/xxx-data",
  "base": "develop",
  "status": {
    "qualityGateStatus": "OK",
    "bugs": 0,
    "vulnerabilities": 0,
    "codeSmells": 0
  },
  "analysisDate": "2020-07-22T11:11:11+0000",
  "url": "https://abc/org/_git/repo/pullrequest/11151",
  "target": "develop"
}
]
}
Run Code Online (Sandbox Code Playgroud)

I need to sort this json by the key value (as this is the easiest way - earlier I had tried sorting by analysisDate) and get the value of qualityGateStatus for that key.

I tried this command to first sort by the key or analysisDate and then tried using key, but I keep getting the error. I thought maybe the value is not a string, so tried to map the key tonumber, but still doesn't work.

jq: error (at <stdin>:0): Cannot index string with string
Run Code Online (Sandbox Code Playgroud)

Commands tried:

jq '.pullRequests[] |sort_by(.analysisDate)[-1].key'
jq '.pullRequests[] | sort_by(.key|tonumber)'
Run Code Online (Sandbox Code Playgroud)

Error:

jq: error (at :0): Cannot index string with string "key"

ogu*_*ail 9

The built-in sort_by accepts an array as input, not a stream of objects. You need to do:

jq '.pullRequests | sort_by(.key)'
Run Code Online (Sandbox Code Playgroud)