dongningce9075 2018-11-20 16:03
浏览 294
已采纳

可以在Go中获取JSON的值

I'm new in Go. I'm trying to read a JSON file and get a part of it for then operate with the values obtained. My JSON is in the file example.json:

{"results":[{"statement_id":0,"series":[{"name":"cpu/node_utilization","columns":["time","distinct"],"values":[[10,1],[11,3],[13,5]]}]}]}

So what I would like to get is the "values" for get the sum of all the elements. In this case: 1+3+5

Here is the code that I have. I'm available to get the results, but then I don't manage to get series.

Here is the code that I have:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    // Open our jsonFile
    jsonFile, err := os.Open("example.json")
    // if we os.Open returns an error then handle it
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("Successfully Opened example.json")
    // defer the closing of our jsonFile so that we can parse it later on
    defer jsonFile.Close()

    byteValue, _ := ioutil.ReadAll(jsonFile)
    var all_data map[string]interface{}
    json.Unmarshal([]byte(byteValue), &all_data)
    fmt.Println(all_data["results"])
}

I've tried diferent solutions like all_data["results"].(map[string]interface{})["series"]) But the problem is that the map is in an array, and I don't know how to solve it.

  • 写回答

2条回答 默认 最新

  • dougong5285 2018-11-20 16:32
    关注

    I have solved defining an Struct.

    package main
    
    import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
    )
    
    
    type AutoGenerated struct {
        Results []struct {
            StatementID int `json:"statement_id"`
            Series      []struct {
                Name    string   `json:"name"`
                Columns []string `json:"columns"`
                Values  [][]int  `json:"values"`
            } `json:"series"`
        } `json:"results"`
    }
    
    func main() {
        // Open our jsonFile
    jsonFile, err := os.Open("example.json")
    // if we os.Open returns an error then handle it
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("Successfully Opened example.json")
    // defer the closing of our jsonFile so that we can parse it later on
    defer jsonFile.Close()
    
    
    byteValue, _ := ioutil.ReadAll(jsonFile)
    all_data := AutoGenerated{}
    json.Unmarshal([]byte(byteValue), &all_data)
    fmt.Println(all_data.Results[0].Series[0].Values)
    }
    

    I have used this web to generate automatically the Struct providing the JSON structure

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大