golang将interface{}转化成[]interface{}、interface{}转化成map、interface{}转化成string

时间:2025-02-21 16:49:06
//将map[string]interface{}转换成map[string][]map[string]string result := make(map[string]interface{}) //1.将interface{}转[]interface{} //取interface{} tmp1 := result["data"] tmpResult, ok := tmp1.([]interface{}) if !ok { log.Print("失败") } //2.将interface{}转map for _, v := range tmpResult { tmp2 := v.(map[string]interface{}) } //3.将interface{}转化成string last := InterfaceToString(tmp2) func InterfaceToString(value interface{}) (s string) { var key string if value == nil { return key } switch value.(type) { case float64: ft := value.(float64) key = strconv.FormatFloat(ft, 'f', -1, 64) case float32: ft := value.(float32) key = strconv.FormatFloat(float64(ft), 'f', -1, 64) case int: it := value.(int) key = strconv.Itoa(it) case uint: it := value.(uint) key = strconv.Itoa(int(it)) case int8: it := value.(int8) key = strconv.Itoa(int(it)) case uint8: it := value.(uint8) key = strconv.Itoa(int(it)) case int16: it := value.(int16) key = strconv.Itoa(int(it)) case uint16: it := value.(uint16) key = strconv.Itoa(int(it)) case int32: it := value.(int32) key = strconv.Itoa(int(it)) case uint32: it := value.(uint32) key = strconv.Itoa(int(it)) case int64: it := value.(int64) key = strconv.FormatInt(it, 10) case uint64: it := value.(uint64) key = strconv.FormatUint(it, 10) case string: key = value.(string) case []byte: key = string(value.([]byte)) default: newValue, _ := json.Marshal(value) key = string(newValue) } return key }