thedevsaddam / gojsonq

A simple Go package to Query over JSON/YAML/XML/CSV Data
https://github.com/thedevsaddam/gojsonq/wiki
MIT License
2.18k stars 140 forks source link

Selecting the average of a property of a group #41

Closed bczifra closed 5 years ago

bczifra commented 5 years ago

Given the following data:

{
  "products": [
    { 
      "name": "foo",
      "price": 10
    },
    { 
      "name": "foo",
      "price": 20
    },
    { 
      "name": "bar",
      "price": 5
    }    
  ]
}

how would I try to query for the average price per distinct name? I've tried .From("products").GroupBy("name").Select("price").Avg(); and .From("products").GroupBy("name").Avg("price") but those both result in NaN.

thedevsaddam commented 5 years ago

Here is a solution:

package main

import (
    "fmt"

    "github.com/thedevsaddam/gojsonq"
)

const data = `{
  "products": [
    { 
      "name": "foo",
      "price": 10
    },
    { 
      "name": "foo",
      "price": 20
    },
    { 
      "name": "bar",
      "price": 5
    }    
  ]
}
`

func main() {
    jq := gojsonq.New().JSONString(data)
    avg := jq.From("products").GroupBy("name").More().From("foo").Avg("price")
    fmt.Printf("Avg: %.3f\n", avg)
}
thedevsaddam commented 5 years ago

@bczifra Hope this will help you. Closing the issue.