【发布时间】:2020-09-30 17:02:19
【问题描述】:
我有以下 JSON 数据。
{
"meta":{
"earliest_ts":1601425980,
"latest_ts":1601482740,
"interval":"minutes",
"level":"cluster",
"entity_id":"xxxxx-xxxxx-xxxxx-xxxxx-xxxxx",
"stat_labels":[
"status_code_classes_per_workspace_total"
],
"entity_type":"workspace",
"start_ts":"1601425980"
},
"stats":{
"cluster":{
"1601431620":{
"3xx":2,
"4xx":87,
"5xx":31,
"2xx":352
},
"1601472780":{
"3xx":14,
"4xx":296,
"5xx":2,
"2xx":3811
},
"1601479140":{
"3xx":17,
"4xx":397,
"5xx":19,
"2xx":4399
}
}
}
}
我尝试对所有 "3xx" 字段取平均值。
使用jq,我设法获得了每个集群的密钥:
echo $data | jq -r '.stats.cluster|keys' | while read key; do
echo $key
done
输出:
[
"1601431620",
"1601472780",
"1601479140"
]
但是当我尝试更进一步时,我无法更进一步并从每个字段中检索数据。 我从this 那里得到了一些启发。
下面的代码不起作用,但你明白了:
# total var will be used to calculate the average
total=$(echo $data | jq ".stats.cluster" | jq length)
# for each cluster ...
echo $data | jq '.stats.cluster|keys' | while read key; do
# ... we retrieve the value "3xx"
i=$($data | jq '.stats.cluster.$key."3xx"')
# ... that we add into a sum var
sum=$(( sum + i ))
done
# we calculate the average
avg=$(( $sum / $total ))
echo "The average is $avg"
我不能像jq '.stats.cluster."1601431620"."3xx"那样直接访问jq中的数据,因为集群太多了,而且一直在变化。
我上面的示例所需的输出是11 和(2 + 14 + 17) / 3,这些数字都来自3xx 的项目字段。
【问题讨论】:
-
请注意,
echo $data引入了自己的错误。 总是引用你的扩展:echo "$data";见I just assigned a variable, butecho $variableshows something else!