使用 jq 对 JSON 中特定字段的值求平均值

Wil*_*ill 2 bash parsing json jq

我有以下 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
         }
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

我尝试对所有字段求平均值"3xx"

使用jq,我设法获取每个集群的密钥:

echo $data | jq -r '.stats.cluster|keys' | while read key; do 
  echo $key
done
Run Code Online (Sandbox Code Playgroud)

输出 :

[
"1601431620",
"1601472780",
"1601479140"
]
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试更进一步时,我无法进一步从每个字段检索数据。我从中得到了一些启发。

下面的代码不起作用,但你明白了:

 # 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"
Run Code Online (Sandbox Code Playgroud)

我无法直接访问 jq 中的数据,jq '.stats.cluster."1601431620"."3xx"因为集群太多并且一直在变化。

我上面的示例所需的输出将是11(2 + 14 + 17) / 3这些数字都来自 的3xxitems 字段。

Ben*_* W. 5

您可以直接从 jq 获取值:

$ jq '[.stats.cluster[]["3xx"]] | add / length' <<< "$data"
11
Run Code Online (Sandbox Code Playgroud)