直接在struct里查询有点难,转成json后使用第三方的库 gojsonq,来查询JSON数据
package main
import (
"fmt"
gojsonq "github.com/thedevsaddam/gojsonq/v2"
)
func main() {
const json = `{"city":"dhaka","type":"weekly","temperatures":[30,39.9,35.4,33.5,31.6,33.2,30.7]}`
avg := gojsonq.New().FromString(json).From("temperatures").Avg()
fmt.Printf("Average temperature: %.2f", avg) // 33.471428571428575
}
执行结果
33.471428571428575