shell 只有在字符串数组中找到值V时,jq才获取字段的所有值

jbose2ul  于 2022-11-16  发布在  Shell
关注(0)|答案(1)|浏览(100)

我 需要 从 数据 对象 数组 中 获取 所有 Distinct " Node " , 前提 是 " ServiceTags " 对象 中 包含 String 元素 " orchestrator " 。
例如 , 对于 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
    }
]

中 的 每 一 个
预期 的 结果 将 是 包含 值 " xyz " 和 " teb " 的 数组 , 因为 存在 作为 " ServiceTags " 属性 的 一 部分 的 " orchestrator " 。
如果 您 能 提供 帮助 , 我 将 不胜 感激 , 我 目前 正在 使用 一 个 基本 shell 脚本 来 执行 此 操作 , 该 脚本 仅 打印 所有 服务 标签 :

# 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

格式

xcitsw88

xcitsw881#

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

将根据orchestrator是否存在于ServiceTags数组中进行筛选,然后为这些对象输出.Node
输出量:

[
  "xyz",
  "teb"
]
Try it online!(第一次)

相关问题