我
json.Unmarshal
JSON 转换为 interface{}
。我无法输入断言它。 http://play.golang.org/p/NAe8voYnb8。
package main
import (
"encoding/json"
"log"
)
func main() {
b := []byte(`{"key1":[
{"apple":"A", "banana":"B", "id": "C"},
{"cupcake": "C", "pinto":"D"}
]
}`)
var data interface{}
_ = json.Unmarshal(b, &data)
log.Println(data)
// map[key1:[map[apple:A id:C banana:B] map[cupcake:C pinto:D]]]
ndata, ok := data.(map[string][]map[string]string)
log.Println(ok, ndata)
// false map[]
key_data, ok := ndata["key1"].([]map[string]string)
log.Println(ok, key_data)
// false []
}
有人知道怎么回事吗?
例如,
package main
import (
"encoding/json"
"log"
)
func somefunc(data interface{}) {
log.Printf("%T\n", data)
// Prints: map[string]interface {}
log.Println(data)
// Correctly prints: map[key1:[map[apple:A id:C banana:B] map[cupcake:C pinto:D]]]
ndata, _ := data.(map[string]interface{})
log.Println(ndata)
// Should print: map[key1:[map[apple:A banana:B id:C] map[cupcake:C pinto:D]]]
key_data, _ := ndata["key1"]
log.Println(key_data)
// Should print: [map[apple:A banana:B id:C] map[cupcake:C pinto:D]]]
}
func main() {
b := []byte(`{"key1":[{"apple":"A", "banana":"B", "id": "C"},{"cupcake": "C", "pinto":"D"}]}`)
var m interface{}
_ = json.Unmarshal(b, &m)
somefunc(m)
}
输出:
2012/10/18 18:21:43 map[string]interface {}
2012/10/18 18:21:43 map[key1:[map[apple:A id:C banana:B] map[cupcake:C pinto:D]]]
2012/10/18 18:21:43 map[key1:[map[banana:B apple:A id:C] map[pinto:D cupcake:C]]]
2012/10/18 18:21:43 [map[banana:B apple:A id:C] map[pinto:D cupcake:C]]
如果您需要一种简单的方法来处理嵌套的 JSON 数据,我已经编写了一个包来做到这一点: https://github.com/opesun/jsonp
这减轻了必须在每个级别键入断言的痛苦。请参阅文档了解说明。
来自 https://pkg.go.dev/encoding/json#Unmarshal:
To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
这些是您需要进行类型断言的类型。