You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jq从JSON数组提取含orchestrator标签的唯一Node值

解决方案

假设你的JSON数据存储在data.json文件中,或通过管道输入(如curl https://example.com/data | ./script.sh),可以用以下改进后的Shell脚本实现需求:

jq -r '
    .[]
    | select(.ServiceTags[] == "orchestrator")
    | .Node
' data.json | sort -u

代码解释

  • .[]:遍历JSON数组中的每一个对象
  • select(.ServiceTags[] == "orchestrator"):筛选出ServiceTags数组包含"orchestrator"元素的对象
  • .Node:提取符合条件对象的Node字段值
  • sort -u:对结果排序并去重,确保输出唯一的Node值

健壮性优化版本

如果JSON中存在ServiceTags字段缺失或为空数组的情况,可以用更健壮的写法避免报错:

jq -r '
    .[]
    | select(.ServiceTags // [] | index("orchestrator") != null)
    | .Node
' data.json | sort -u
  • .ServiceTags // []:若ServiceTags字段不存在,默认视为空数组
  • index("orchestrator") != null:检查数组中是否包含目标元素,比直接遍历更稳妥

示例验证

假设你的data.json内容如下:

[
{"Node": "abc", "ServiceTags": ["web", "api"]},
{"Node": "xyz", "ServiceTags": ["orchestrator", "manager"]},
{"Node": "teb", "ServiceTags": ["worker", "orchestrator"]},
{"Node": "xyz", "ServiceTags": ["orchestrator"]}
]

运行脚本后输出:

teb
xyz

如果你的原始脚本只是打印所有ServiceTags(比如jq -r '.[].ServiceTags[]' data.json),直接替换为上述逻辑即可完成需求。

内容的提问来源于stack exchange,提问作者Carlos Armas Ramirez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:15:40