Select value field out of possible similar key names

Viewed 56

I have a pom.json with a bug in it:

{
        "Components": [
                {
                        "ARTIFACTID": "good artifact",
                        "BuildJobDate": "2020-01-20T16:39:50"
                },
                {
                        "ARTIFACT_ID": "bad artifact",
                        "BuildJobDate": "'2021-11-29T17:23:39'"
                },
                {
                        "ARTIFACTID": "another good artifact",
                        "BuildJobDate": "2022-01-26T21:18:20"
                }
        ]
}

in my install script I collect all ARTIFACTID:

local -ra artifacts=( $(jq -r '.Components | .[].ARTIFACTID' "$manifest") )

tried to fix it by .[] | {ARTIFACTID, ARTIFACT_ID} but can't understand how to leave only the valid values

my question is: is there is a way to select field out of possible fields in jq ?

1 Answers

Use a select expression with a boolean condition

.Components | map(select(.ARTIFACTID or .ARTIFACT_ID))

Doing {ARTIFACTID, ARTIFACT_ID} requires either of the keys to be present in the resultant object. So if either of the keys are not present they are updated with null. Using select clause evaluates the expression and produces the result into the object only if it evaluates to true

jqplay - demo

Related