简体   繁体   English

如何在 GO 中访问 JSON 的字段

[英]How to access fields of a JSON in GO

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.大家好,我想看看从 go 中的 http.get 请求访问 json 对象的字段的正确方法是什么。

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?我首先做一个 http.get 调用获取 JSON 然后打印它(这有效)但是有没有办法只访问一个字段?

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?有没有办法只打印 Json 的“测试”? What is the proper way of accessing that field?访问该字段的正确方法是什么?

Use encoding/json package to Unmarshal data into struct, like following.使用encoding/json包将数据解组到结构中,如下所示。

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.您还可以将Test解析为特定的结构。

Same as the previous answer, use encoding/json package to Unmarshal data.与上一个答案相同,使用 encoding/json 包来解组数据。 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.但是如果你不想指定结构,你可以使用 map[string]interface/bson.M{} 来接收数据,获取字段,然后转换成你想要的类型。

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

You may want to try gabs container, if you are not sure how depth JSON hierarchy can be.如果您不确定 JSON 层次结构的深度,您可能想尝试 gabs 容器。 Have a look at below resources看看下面的资源

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

If you just want to access one field then you can use the jsonq module https://godoc.org/github.com/jmoiron/jsonq如果您只想访问一个字段,那么您可以使用 jsonq 模块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).其中 jq 是从上面的 JSON 构造的 jsonq 查询对象(有关如何从 JSON 流或字符串创建查询对象的说明,请参见 godoc 页面)。

You can also use this library for retrieving specific String, Integer, Float and Bool values at an arbitrary depth inside a JSON object.您还可以使用此库在 JSON 对象内的任意深度检索特定的 String、Integer、Float 和 Bool 值。

Since you are starting with a URL, Decode is a better option than Unmarshal :由于您从 URL 开始,因此Decode是比Unmarshal更好的选择:

package main

import (
   "encoding/json"
   "net/http"
)

func main() {
   r, e := http.Get("https://github.com/manifest.json")
   if e != nil {
      panic(e)
   }
   defer r.Body.Close()
   var s struct { Name string }
   json.NewDecoder(r.Body).Decode(&s)
   println(s.Name == "GitHub")
}

https://golang.org/pkg/encoding/json#Decoder.Decode https://golang.org/pkg/encoding/json#Decoder.Decode

You may check this https://github.com/valyala/fastjson你可以检查这个https://github.com/valyala/fastjson

s := []byte(`{"foo": [123, "bar"]}`)
    fmt.Printf("foo.0=%d\n", fastjson.GetInt(s, "foo", "0"))

    // Output:
    // foo.0=123

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM