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\n", key, str) case float64: fmt.Printf("m[%s] value type is float64, = %f\n", key, data) case bool: fmt.Printf("m[%s] value type is bool, = %v\n", key, data) case []interface{}: fmt.Printf("m[%s] value type is []interface{}, = %v\n", 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方式需要一個一個進行斷言判斷才行
