How to calculate average using jq from JSON output

Viewed 2330

This is the exact JSON for which i am trying to parse with jq to get an average

{
    "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
            }
        }
    ]
}

Using .Datapoints[]|select(.ExtendedStatistics.p80 >=0 )| [.ExtendedStatistics.p80] | @tsv gives me

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

I am trying to get an average of all the numbers How do i get a single number as output Expected Output

3.216756656748

Calculated as

Average:    16.08378328374 / 5 = 3.216756656748
1 Answers

You can create a single array instead of an array per entry, then pipe it to the filter add and the filter length, which will add the numbers in the array and compute the length of the array. FInally, you divide the results of both filters and... voila!

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