使用jq对JSON中特定字段的值进行平均
我有以下JSON数据使用jq对JSON中特定字段的值进行平均,json,bash,parsing,jq,Json,Bash,Parsing,Jq,我有以下JSON数据 { "meta":{ "earliest_ts":1601425980, "latest_ts":1601482740, "interval":"minutes", "level":"cluster", "entity_id":"xxxxx-
{
"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"
]
但是,当我试图更进一步时,我无法进一步从每个字段检索数据。
我从你那儿得到一些消息
下面的代码不起作用,但您可以理解:
# 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的items字段。您可以直接从jq获得值:
$ jq '[.stats.cluster[]["3xx"]] | add / length' <<< "$data"
11
请注意,echo$data引入了它自己的bug。始终引用您的扩展:echo$data;看见