给定这些数据,我将尝试返回servers
数组,其中包含基于s_Group
值的groups
数组中的任何匹配项。然而,group_by(s_Group)
只返回两个数组的公共值(有一个无关的不匹配,我无法解释(。值得一提的是,这是在bash脚本中完成的,所以我可以将数组分解为单独的文件和/或多个步骤,如果这样做更容易的话。
EDIT:我应该指定我希望groups
中的所有属性都被拉到发生匹配的新servers
元素中。抱歉没有说清楚。添加一个";期望输出";。
输入数据:
{
"servers": [
{
"location": "srv_apc1",
"f_Group": "auc-1"
},
{
"location": "srv_apc2",
"f_Group": "auc-1",
"c_Group": "c1"
},
{
"location": "srv_apc3",
"f_Group": "auc-1",
"c_Group": "c2"
},
{
"location": "srv_apc4",
"f_Group": "auc-1",
"c_Group": "c3"
},
{
"location": "srv_wc1",
"s_Group": "cb-1"
},
{
"location": "srv_wc2",
"s_Group": "cb-2"
},
{
"location": "srv_wc3",
"s_Group": "cb-3"
},
{
"location": "srv_wc4",
"s_Group": "cb-4"
}
],
"groups": [
{
"s_Group": "cb-1",
"options": [
"opt1",
"opt3",
"opt5",
"home"
]
},
{
"s_Group": "cb-2",
"options": [
"opt2",
"opt4",
"opt6",
"home"
]
},
{
"s_Group": "cb-3",
"options": [
"opt7",
"opt8",
"opt9",
"home",
"print"
]
},
{
"s_Group": "cb-4",
"options": [
"ems99",
"erec98",
"expr-77",
"home"
]
},
{
"s_Group": "extra-99",
"options": [
"conf1",
"ems34",
"erec1",
"home",
"chec99",
"franT"
]
}
]
}
jq:
.servers + .groups | group_by(.s_Group) | map(add)
演示
期望输出:
{
"servers": [
[
{
"location": "srv_apc1",
"f_Group": "auc-1"
},
{
"location": "srv_apc2",
"f_Group": "auc-1",
"c_Group": "c1"
},
{
"location": "srv_apc3",
"f_Group": "auc-1",
"c_Group": "c2"
},
{
"location": "srv_apc4",
"f_Group": "auc-1",
"c_Group": "c3"
},
{
"location": "srv_wc1",
"s_Group": "cb-1",
"options": [
"opt1",
"opt3",
"opt5",
"home"
]
},
{
"location": "srv_wc2",
"s_Group": "cb-2",
"options": [
"opt2",
"opt4",
"opt6",
"home"
]
},
{
"location": "srv_wc3",
"s_Group": "cb-3",
"options": [
"opt7",
"opt8",
"opt9",
"home",
"print"
]
},
{
"location": "srv_wc4",
"s_Group": "cb-4",
"options": [
"ems99",
"erec98",
"expr-77",
"home"
]
}
]
]
}
所有事情都可以通过一次jq调用来完成。如果我正确理解需求,你可以使用以下jq程序:
INDEX(.groups[] | select(.s_Group); .s_Group) as $dict
| .servers |= map( . + $dict[.s_Group // ""])
| {servers : [.servers] }
这返回所示的所需输出,除了相对于"0"的明显差异之外;s_组":"cb-4";。
在.servers
项目上使用JOIN
和INDEX
:
jq '{servers: [JOIN(
INDEX(.groups[]; .s_Group); .servers[]; .s_Group // empty; add
)]}'
{
"servers": [
{
"location": "srv_apc1",
"f_Group": "auc-1"
},
{
"location": "srv_apc2",
"f_Group": "auc-1",
"c_Group": "c1"
},
{
"location": "srv_apc3",
"f_Group": "auc-1",
"c_Group": "c2"
},
{
"location": "srv_apc4",
"f_Group": "auc-1",
"c_Group": "c3"
},
{
"location": "srv_wc1",
"s_Group": "cb-1",
"options": [
"opt1",
"opt3",
"opt5",
"home"
]
},
{
"location": "srv_wc2",
"s_Group": "cb-2",
"options": [
"opt2",
"opt4",
"opt6",
"home"
]
},
{
"location": "srv_wc3",
"s_Group": "cb-3",
"options": [
"opt7",
"opt8",
"opt9",
"home",
"print"
]
},
{
"location": "srv_wc4",
"s_Group": "cb-4",
"options": [
"emsar",
"ereceipt",
"expressmtreceive",
"home",
"mtagentlookup",
"mtreceive",
"mtstatus"
]
}
]
}
演示