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

  • 本文关键字:jq 字段 数组 字符串 shell jq
  • 更新时间 :
  • 英文 :


我需要获取所有Distinct"节点";仅当在数据对象的数组中;ServiceTags";具有字符串元素";"管弦乐队";。

例如,对于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
}
]

预期的结果将是一个包含值"0"的数组;xyz";以及";teb";因为存在一个";管弦乐队;作为";ServiceTags";所有物

如果有任何帮助,我将不胜感激,我目前正在一个只打印所有ServiceTags:的基本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
map(select(.ServiceTags | index("orchestrator")).Node)

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


输出:

[
"xyz",
"teb"
]

在线试用

最新更新