[英]Do I need to define the exact same structure of a JSON to use it with json.Unmarshal?
我正在獲取一個 subreddit 並將其作為 JSON 響應接收。
問題是回報有點大,有很多領域,但我只想要其中一些。
結構類似於:
data.children.data.fields
Children 是一個數組,所以我不能像我想象的那樣訪問它,但這只是一個例子。
我將 JSON 粘貼到 QuickType 上以查看它返回的內容,結構很大。
那么,有沒有辦法只獲取我想使用 json.Unmarshal 的字段?
希望有人可以幫助我,在此先感謝!
您可以將結構與您想要的字段一起使用。 看下面的例子
package main
import (
"encoding/json"
"fmt"
)
type Test struct {
Field1 int `json:"field1"`
Field2 string `json:"field2"`
}
func main() {
jsonString := `{
"field1": 1,
"field2": "test field 2",
"field3": "test field 3"
}`
t := Test{}
err := json.Unmarshal([]byte(jsonString), &t)
if err != nil {
fmt.Println(err)
}
fmt.Println("\n", t)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.