初级会员
  • 第 58483 位会员
  • YYYGH
  • 2020-12-06 18:47:01
  • Offline
  • 20 15

最近发布的主题

    暂无

最近发布的文章

    暂无

最近分享的资源

    暂无

最近发布的项目

    暂无

最近的评论

  • ``` type Person struct { Age string `json:"status"` Data Data `json:"data"` Name string `json:"name"` } type Data struct { Values []map[string]interface{} `json:"result"` } func main() { // 假数据 b := []byte(`{"status":"success","wmd":{"result":"wmd"},"name":"wmd","data":{"resultType":"matrix","result":[{"metric":{"__name__":"namedprocess_namegroup_memory_bytes","groupname":"root","instance":"localhost:9256","job":"process_export_9256","memtype":"resident"},"values":[[1635991200,"300257280"],[1635993000,"302428160"],[1635994800,"301727744"]]}]}}`) var p Person err := json.Unmarshal(b, &p) if err != nil { fmt.Println(err) } wmd := p.Data.Values[0]["values"] /* 下面这种方法可行,建议最好根据api返回的数据格式定义struct 去解决 */ list := wmd.([]interface{}) sum := float64(0) for _, v := range list { value := v.([]interface{}) for _, data := range value { switch data := data.(type) { case string: i, _ := strconv.ParseFloat(data, 64) sum += i case float64: sum += data } } } fmt.Printf("%f\n", sum) } ```
  • package main import ( "encoding/json" "fmt" ) type Person struct { Age string `json:"status"` Data Data `json:"data"` Name string `json:"name"` } type Data struct { Values []map[string]interface{} `json:"result"` } func main() { // 假数据 b := []byte(`{"status":"success","wmd":{"result":"wmd"},"name":"wmd","data":{"resultType":"matrix","result":[{"metric":{"__name__":"namedprocess_namegroup_memory_bytes","groupname":"root","instance":"localhost:9256","job":"process_export_9256","memtype":"resident"},"values":[[1635991200,"300257280"],[1635993000,"302428160"],[1635994800,"301727744"]]}]}}`) var p Person err := json.Unmarshal(b, &p) if err != nil { fmt.Println(err) } wmd := p.Data.Values[0]["values"] /* 下面这种方法可行,建议最好根据api返回的数据格式定义struct 去解决 */ list := wmd.([]interface{}) sum := float64(0) for _, v := range list { value := v.([]interface{}) for _, data := range value { switch data := data.(type) { case string: i, _ := strconv.ParseFloat(data, 64) sum += i case float64: sum += data } } } fmt.Printf("%f\n", sum) }