thedevsaddam / gojsonq

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

How access array of objects using gojsonq? #70

Closed jaylahoti closed 4 years ago

jaylahoti commented 4 years ago

const json = [{"city":"dhaka","type":"weekly","temperatures":[30,39.9,35.4,33.5,31.6,33.2,30.7]}]

avg := gojsonq.New().JSONString(json).From("[0].temperatures").Avg() Above code does not work.

How can it be done?

thedevsaddam commented 4 years ago

This should work

package main

import (
    "fmt"

    "github.com/thedevsaddam/gojsonq"
)

func main() {
    const json = `[{"city":"dhaka","type":"weekly","temperatures":[30,39.9,35.4,33.5,31.6,33.2,30.7]}]`
    result := gojsonq.New().FromString(json).From("[0].temperatures").Avg() // handle error
    fmt.Printf("%#v\n", result)
}

//output: 33.471428571428575

Golang play link: https://play.golang.org/p/YS2sUm_DHv3