Home > database >  jq obtain all values of a field only if inside string array the value V is found
jq obtain all values of a field only if inside string array the value V is found

Time:10-14

I need to get all Distinct "Node" from an array of data objects only if in the object the "ServiceTags" has the String element "orchestrator".

For example, for the json:

[
    {
        "Node": "abc",
        "ServiceTags": [],
        "Type": "",
        "Definition": {
            "Interval": "0s",
            "Timeout": "0s"
        },
        "CreateIndex": 11241543,
        "ModifyIndex": 11241543
    },
    {
        "Node": "xyz",
        "ServiceTags": [
            "rules",
            "rhdm_es",
            "rhdm",
            "orchestrator"
        ],
        "Type": "http",
        "Definition": {
            "Interval": "0s",
            "Timeout": "0s"
        },
        "CreateIndex": 12907642,
        "ModifyIndex": 12907659
    },
    {
        "Node": "teb",
        "ServiceTags": [
            "rules",
            "orchestrator"
        ],
        "Type": "http",
        "Definition": {
            "Interval": "0s",
            "Timeout": "0s"
        },
        "CreateIndex": 12907642,
        "ModifyIndex": 12907659
    },
    {
        "Node": "iry",
        "ServiceTags": [
            "rules"
        ],
        "Type": "http",
        "Definition": {
            "Interval": "0s",
            "Timeout": "0s"
        },
        "CreateIndex": 12907642,
        "ModifyIndex": 12907659
    }
]

the expected result would be an array that contains the values "xyz" and "teb" because there is a "orchestrator" as part of "ServiceTags" property.

I would appreciate any help, I'm currently making this in a basic shell script that only prints all the ServiceTags:

# Get consul data in json format
consulResult=$(cat -)

# Validate if the json is not null or empty
if [ -z "$consulResult" ];
then
    echo "NULL OR EMPTY";
else
        echo "Not NULL";
        echo $consulResult | jq '.[].ServiceTags'
fi

CodePudding user response:

map(select(.ServiceTags | index("orchestrator")).Node)

Will filter based on if orchestrator exist in the ServiceTags array, then output .Node for those objects


Output:

[
  "xyz",
  "teb"
]

Try it online!

  • Related