dongningce9075 2018-11-20 08:03
浏览 295
已采纳

可以在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 08: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部