I'm new to Go and can't figure out how to simply read and average the values of an array of JSONs. I also want to round my result to 1 decimal point, but Go has no Round()
function. Here's the data:
[
{"millisUTC":"1496424000000","price":"7.6"},
{"millisUTC":"1496423700000","price":"7.5"},
{"millisUTC":"1496423400000","price":"9.1"},
{"millisUTC":"1496423100000","price":"9.2"},
{"millisUTC":"1496422800000","price":"10.0"}
]
I want to get the prices and average them, rounding to 1 decimal point. Yet it took me over 30 lines of code, when (as a Ruby developer) it would usually take me 3 lines. How do I simplify this? My code takes in 2 parameters, starttime
and endtime
, and calls an API: https://github.com/rayning0/griddy/blob/master/controllers/default.go
type arrayOfMaps []map[string]string
func getAvgPrice(starttime, endtime string) float64 {
response, err := http.Get("https://hourlypricing.comed.com/api?type=5minutefeed&datestart=" + starttime + "&dateend=" + endtime)
if err != nil {
fmt.Println(err)
}
defer response.Body.Close()
energyJSON, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
var energyPrices arrayOfMaps
err = json.Unmarshal(energyJSON, &energyPrices)
fmt.Println("Energy prices between", starttime, "and", endtime)
fmt.Println(energyPrices)
var sum float64
var size int
for _, p := range energyPrices {
price, _ := strconv.ParseFloat(p["price"], 64)
sum += price
size++
}
avg := Truncate(sum / float64(size))
fmt.Println("Average price:", avg)
return avg
}
//Truncate a float to 1 level of precision
func Truncate(some float64) float64 {
return float64(int(some*10)) / 10
}
Edited, thanks to excellent help from @icza!
This applies to my question: https://golang.org/pkg/encoding/json/#Decoder.Decode
See my revised solution, with detailed comments: https://github.com/rayning0/griddy/blob/master/controllers/default.go