I have one script ./getClasses.sh
which returns comma separated list like ApexClass1,ApexClass2
. There are more than two items in this list.
I want to use that list in jq
to filter out JSON values by a certain key value, which coincides with one value from the list
I tried in
operator
echo $(cat tests.json) | jq '.result.coverage.coverage[] | select(.name included($(./getClasses.sh)))'
and includes
operator
echo $(cat tests.json) | jq '.result.coverage.coverage[] | select(.name in($(./getClasses.sh)))'
but both of them are failing with en error
jq: error: syntax error, unexpected IDENT, expecting ';' or ')' (Unix shell quoting issues?) at <top-level>, line 1:
File tests.json
contains a following JSON
{"status": 0,
"result": {
"summary": {
"outcome": "Passed",
"testsRan": 13,
"passing": 13,
"failing": 0,
"skipped": 0,
"passRate": "100%",
"failRate": "0%"}, "tests": [], "coverage": {
"coverage": [
{
"name": "ApexClass1",
"totalLines": 25,
"lines": {},
"totalCovered": 23,
"coveredPercent": 92}, {
"name": "ApexClass2",
"totalLines": 25,
"lines": {},
"totalCovered": 23,
"coveredPercent": 92}, {
"name": "ApexClass3",
"totalLines": 25,
"lines": {},
"totalCovered": 23,
"coveredPercent": 92}
],
"records": []
} } }
How can I achieve the desired output?
CodePudding user response:
I think I got it.
I need to pass the strings as argument and then split it by comma and unbracket them like this:
classes=$(./getClasses.sh)
echo $(cat tests.json) | jq --arg classes $classes '.result.coverage.coverage[] | select(.name == ($classes | split(",")[])) | .totalLines' | awk '{s =$1} END {print s}'
CodePudding user response:
Another option using inside()
[docs] to check if .name
exist in an array.
The array is build using: "ApexClass1,AapexClass2" | split(",")
[docs]
jq '[ .result.coverage.coverage[] | select([ .name ] | inside("ApexClass1,AapexClass2" | split(",") ) ) | . ]' tests.json
[
{
"name": "ApexClass1",
"totalLines": 25,
"lines": {},
"totalCovered": 23,
"coveredPercent": 92
},
{
"name": "ApexClass2",
"totalLines": 25,
"lines": {},
"totalCovered": 23,
"coveredPercent": 92
}
]
Online JqPlay Demo
Local demo:
➜ find="ApexClass1,ApexClass3"
➜
➜ jq --arg find $find '[ .result.coverage.coverage[] | select([ .name ] | inside($find | split(",") ) ) | . ]' tests.json
[
{
"name": "ApexClass1",
"totalLines": 25,
"lines": {},
"totalCovered": 23,
"coveredPercent": 92
},
{
"name": "ApexClass3",
"totalLines": 25,
"lines": {},
"totalCovered": 23,
"coveredPercent": 92
}
]
➜