-
慕工程0101907
不要声明你不想要的字段。https://play.golang.org/p/cQeMkUCyFypackage mainimport ( "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))或者。它会吞下所有的转换错误。m := make(map[string]string)json.Unmarshal([]byte(test), interface{}(&m))fmt.Printf("%#v\n", m)fmt.Println(m["title"])
-
皈依舞
要扩展 Darigaaz 的答案,您还可以使用在解析函数中声明的匿名结构。这避免了必须让包级别的类型声明在单一用例的代码中乱扔垃圾。https://play.golang.org/p/MkOo1KNVbspackage mainimport ( "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)}
-
浮云间
查看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)