3 回答

TA貢獻1887條經(jīng)驗 獲得超5個贊
不要聲明你不想要的字段。
https://play.golang.org/p/cQeMkUCyFy
package main
import (
"fmt"
"encoding/json"
)
type Struct struct {
Title string `json:"title"`
}
func main() {
test := `{
"title": "Found a bug",
"body": "I'm having a problem with this.",
"assignee": "octocat",
"milestone": 1,
"labels": [
"bug"
]
}`
var s Struct
json.Unmarshal([]byte(test), &s)
fmt.Printf("%#v", s)
}
或者,如果您想完全擺脫結構:
var i interface{}
json.Unmarshal([]byte(test), &i)
fmt.Printf("%#v\n", i)
fmt.Println(i.(map[string]interface{})["title"].(string))
或者。它會吞下所有的轉(zhuǎn)換錯誤。
m := make(map[string]string)
json.Unmarshal([]byte(test), interface{}(&m))
fmt.Printf("%#v\n", m)
fmt.Println(m["title"])

TA貢獻1851條經(jīng)驗 獲得超3個贊
要擴展 Darigaaz 的答案,您還可以使用在解析函數(shù)中聲明的匿名結構。這避免了必須讓包級別的類型聲明在單一用例的代碼中亂扔垃圾。
https://play.golang.org/p/MkOo1KNVbs
package main
import (
"encoding/json"
"fmt"
)
func main() {
test := `{
"title": "Found a bug",
"body": "I'm having a problem with this.",
"assignee": "octocat",
"milestone": 1,
"labels": [
"bug"
]
}`
var s struct {
Title string `json:"title"`
}
json.Unmarshal([]byte(test), &s)
fmt.Printf("%#v", s)
}

TA貢獻1829條經(jīng)驗 獲得超4個贊
查看go-simplejson
例子:
js, err := simplejson.NewJson([]byte(`{
"test": {
"string_array": ["asdf", "ghjk", "zxcv"],
"string_array_null": ["abc", null, "efg"],
"array": [1, "2", 3],
"arraywithsubs": [{"subkeyone": 1},
{"subkeytwo": 2, "subkeythree": 3}],
"int": 10,
"float": 5.150,
"string": "simplejson",
"bool": true,
"sub_obj": {"a": 1}
}
}`))
if _, ok = js.CheckGet("test"); !ok {
// Missing test struct
}
aws := js.Get("test").Get("arraywithsubs")
aws.GetIndex(0)
- 3 回答
- 0 關注
- 155 瀏覽
添加回答
舉報