在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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方式需要一个一个进行断言判断才行 |
请发表评论