How to access fields of a JSON in GO

我与影子孤独终老i 提交于 2021-02-07 03:08:17

问题


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?


回答1:


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.




回答2:


Same as the previous answer, use encoding/json package to Unmarshal data. But if you don't want to specify the structure, you could use map[string]interface/bson.M{} to receive the data, and get the field, then cast into types your want.

m := make(map[string]interface{})
err := json.Unmarshal(data, &m)
if err != nil {
    log.Fatal(err)
}
fmt.Println(m["id"])



回答3:


You may want to try gabs container, if you are not sure how depth JSON hierarchy can be. Have a look at below resources

https://github.com/Jeffail/gabs https://godoc.org/github.com/Jeffail/gabs




回答4:


If you just want to access one field then you can use the jsonq module https://godoc.org/github.com/jmoiron/jsonq

For your example you could get the test object with code similar to

jq.Object("test")

Where jq is a jsonq query object constructed from your JSON above (see the godoc page for instructions on how to create a query object from a JSON stream or string).

You can also use this library for retrieving specific String, Integer, Float and Bool values at an arbitrary depth inside a JSON object.



来源:https://stackoverflow.com/questions/35660467/how-to-access-fields-of-a-json-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!