【问题标题】:Perform average of values of a particular field inside a JSON using jq使用 jq 对 JSON 中特定字段的值进行平均
【发布时间】: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 的项目字段。

【问题讨论】:

标签: json bash parsing jq


【解决方案1】:

可以直接从jq获取值:

$ jq '[.stats.cluster[]["3xx"]] | add / length' <<< "$data"
11

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-11
    • 2019-06-27
    • 1970-01-01
    • 2017-01-06
    • 2019-07-07
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多