Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

sorting

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"
}
]
}

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

Commands tried:

jq '.pullRequests[] |sort_by(.analysisDate)[-1].key'
jq '.pullRequests[] | sort_by(.key|tonumber)'

Error:

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

like image 921
AK123 Avatar asked Jul 19 '26 20:07

AK123


2 Answers

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

jq '.pullRequests | sort_by(.key)'
like image 130
oguz ismail Avatar answered Jul 21 '26 10:07

oguz ismail


If, as indicated in the comments, the actual goal is essentially to find the maximum value by .key, then it would be better to use max_by rather than sort_by. Based on the comments, the following would suffice:

.pullRequests
| max_by(.key).status.qualityGateStatus
like image 35
peak Avatar answered Jul 21 '26 09:07

peak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!