jstr := `{"01":[{"year":1662,"title":"ggg"},{"year":1835,"title":"uuuu"}]}` var data map[string]interface{} //data := map[string]interface{}{} //上面两种定义都可以,第二种要怎么理解,为什么要加{}? _ = json.Unmarshal([]byte(jstr), &data) //title := data["01"].([]map[string]interface{})[0]["title"] //不行 title := data["01"].([]interface{})[0].(map[string]interface{})["title"] //为什么上面的方式不行,下面的行? fmt.Println(title.(string))
![]() | 1 GogoGo666 2023-02-13 15:54:30 +08:00 你的代码中使用 var 关键字声明的 data 没有初始化,:=声明的变量是已经初始化的,{}表示没有任何键值对 第二个问题因为你的 json 结构决定的,01 这个 key ,对应的 value 的最顶层是个[] |
2 DefoliationM 2023-02-13 17:55:05 +08:00 上面只有类型,下面有初始化 **************************** {} -> 键值对,[] -> 数组 |
3 xuyang2 2023-02-13 18:29:40 +08:00 因为 Go 不是 Java []interface{} 不是 []map[string]interface{} panic 报错信息已经说的很清楚了 |
4 Seanfuck OP @xuyang2 我的疑问是为什么 []interface{} 和 map[string]interface{} 可以,[]map[string]interface{} 却不行, 我现在理解为前两者是“类型”,后者是“类型数组”所以不行,这样对不? |
5 Seanfuck OP 我又试了自定义类型 ``` type Evt struct { Year int `json:"year"` Title string `json:"title"` } ``` 编译无错但运行报错: ``` jstr := `[{"01":[{"year":1662,"title":"ggg"},{"year":1835,"title":"uuuu"}]}]` var data3 []map[string]interface{} _ = json.Unmarshal([]byte(jstr), &data3) title3 := data3[0]["01"].([]interface{})[0].(Evt).Title fmt.Println(title3) ``` 这又是怎么回事,是否不能用结构体类型?求教。 |
![]() | 6 yaott2020 2023-02-14 09:41:22 +08:00 via Android 你不用先断言吗 |