如何使用 JSON 输出中的 jq 计算平均值

How to calculate average using jq from JSON output

这正是我尝试使用 jq 解析以获得平均值的 JSON

{
    "Label": "CPUUtilization",
    "Datapoints": [
        {
            "Timestamp": "2020-02-20T18:35:00Z",
            "Unit": "Percent",
            "ExtendedStatistics": {
                "p80": 7.39284928374
            }
        },
        {
            "Timestamp": "2020-02-20T18:00:00Z",
            "Unit": "Percent",
            "ExtendedStatistics": {
                "p80": 2.234234
            }
        },
        {
            "Timestamp": "2020-02-20T18:45:00Z",
            "Unit": "Percent",
            "ExtendedStatistics": {
                "p80": 2.4567
            }
        },
        {
            "Timestamp": "2020-02-20T18:50:00Z",
            "Unit": "Percent",
            "ExtendedStatistics": {
                "p80": 2.0
            }
        },

        {
            "Timestamp": "2020-02-20T18:20:00Z",
            "Unit": "Percent",
            "ExtendedStatistics": {
                "p80": 2.0
            }
        }
    ]
}

使用.Datapoints[]|select(.ExtendedStatistics.p80 >=0 )| [.ExtendedStatistics.p80] | @tsv 给我

"7.39284928374"
"2.234234"
"2.4567"
"2"
"2" 

我正在尝试获取所有数字的平均值 我如何获得一个数字作为输出 预期输出

3.216756656748

计算为

Average:    16.08378328374 / 5 = 3.216756656748

您可以创建一个数组而不是每个条目一个数组,然后将其通过管道传递给过滤器添加和过滤器长度,这将添加数组中的数字并计算数组的长度。最后,您将两个过滤器的结果相除,然后......瞧!

jq '[.Datapoints[] | select(.ExtendedStatistics.p80>=0) | .ExtendedStatistics.p80] | add/length' file.json