doutou7549 2016-02-26 11:50
浏览 117
已采纳

如何在GO中访问JSON的字段

Hi everyone I'm trying to see what the proper way of accessing fields of a json object from a http.get request in go.

I first do an http.get call get the JSON and then print it (which works) but is there a way to access just a field?

for example:

response, err:= http.Get("URL")
//Error checking is done between
contents, err:=ioutil.Readall(response.Body)

//Now at this point I have a json that looks like
{"id": "someID", 
"name": "someName", 
"test": [{"Name":"Test1", 
          "Result": "Success"},
         {"Name":"Test2", 
          "Result": "Success"},
         {...},
]}

Is there a way to only print the "test" of the Json? What is the proper way of accessing that field?

  • 写回答

4条回答 默认 最新

  • duandan1995 2016-02-26 11:57
    关注

    Use encoding/json package to Unmarshal data into struct, like following.

    type Result struct {
        ID   string        `json:"id"`
        Name string        `json:"name"`
        Test []interface{} `json:"test"`
    }
    
    var result Result
    json.Unmarshal(contents, &result)
    fmt.Println(result.Test)
    

    You can also parse Test to specific struct.

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

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部