如何在GO中访问JSON的字段

huangapple go评论76阅读模式
英文:

How to access fields of a JSON in GO

问题

大家好,我正在尝试找出在Go语言中从http.get请求中访问JSON对象字段的正确方法。

首先,我进行了一个http.get调用来获取JSON并打印它(这个步骤已经完成),但是有没有一种方法只访问一个字段呢?

例如:

response, err := http.Get("URL")
// 错误检查在这之间进行
contents, err := ioutil.ReadAll(response.Body)

// 现在,在这一点上,我有一个看起来像这样的JSON
{"id": "someID",
"name": "someName",
"test": [{"Name":"Test1",
          "Result": "Success"},
         {"Name":"Test2",
          "Result": "Success"},
         {...},
]}

有没有一种方法只打印JSON中的"test"字段?访问该字段的正确方法是什么?

英文:

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

得分: 14

使用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)

你还可以将Test解析为特定的结构体。

英文:

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

得分: 10

与上一个答案相同,使用encoding/json包来解析数据。但是,如果你不想指定结构,可以使用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"])
英文:

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

得分: 1

你可以尝试使用gabs容器,如果你不确定JSON层次结构的深度。请查看以下资源:

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

英文:

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

得分: 1

如果您只想访问一个字段,您可以使用jsonq模块https://godoc.org/github.com/jmoiron/jsonq

对于您的示例,您可以使用类似以下代码获取test对象:

jq.Object("test")

其中jq是从您上面的JSON构建的jsonq查询对象(请参阅godoc页面以了解如何从JSON流或字符串创建查询对象的说明)。

您还可以使用此库在JSON对象的任意深度内检索特定的字符串、整数、浮点数和布尔值。

英文:

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.

答案5

得分: 1

由于您从一个URL开始,DecodeUnmarshal更好:

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

英文:

Since you are starting with a URL, Decode is a better option than 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

答案6

得分: 0

你可以查看这个链接 https://github.com/valyala/fastjson

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

// 输出:
// foo.0=123

英文:

You may check this 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

huangapple
  • 本文由 发表于 2016年2月27日 03:50:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/35660467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定