package main import ( "encoding/json" "fmt" ) var str string func main() { m := make(map[string]interface{}, 4) jsonbuf := `{"company":"zyg","isok":true,"price":5.55,"subjects":["go","python","java"]}` err := json.Unmarshal([]byte(jsonbuf), &m) if err != nil { return } for key, value := range m{ switch data := value.(type) { case string: str = data fmt.Printf("m[%s] value type is string, = %s ", key, str) case float64: fmt.Printf("m[%s] value type is float64, = %f ", key, data) case bool: fmt.Printf("m[%s] value type is bool, = %v ", key, data) case []interface{}: fmt.Printf("m[%s] value type is []interface{}, = %v ", key, data) } } }
执行的结果为
m[isok] value type is bool, = true m[price] value type is float64, = 5.550000 m[subjects] value type is []interface{}, = [go python java] m[company] value type is string, = zyg
这里可以看到,将json解析到map与解析到结构各有各的好处,在声明上,结构体需要声明结构类型,而map只需要一个make函数,但是一旦得到了值以后,结构休的方式可以直接操作,map方式需要一个一个进行断言判断才行