// Strval 獲取變量的字符串值 // 浮點(diǎn)型 3.0將會(huì)轉(zhuǎn)換成字符串3, "3" // 非數(shù)值或字符類型的變量將會(huì)被轉(zhuǎn)換成JSON格式字符串 func Strval(value interface{}) 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 }
補(bǔ)充:golang json 為map[string] interface{}
{"sn":1,"ls":false,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"sc":0,"w":"還"}]},{"bg":0,"cw":[{"sc":0,"w":"有點(diǎn)"}]},{"bg":0,"cw":[{"sc":0,"w":"眼熟"}]}]}
需要將json格式中的w字段取出來,并且拼成結(jié)果串進(jìn)行展示
1、從json數(shù)組中獲取ws
2、ws是數(shù)組,數(shù)組元素為object
3、cw是數(shù)組,數(shù)組元素為object
4、w是string
5、從cw遍歷獲取w字段
func RecResultJsonToPlain() { var recResult string var dat map[string]interface{} json.Unmarshal([]byte(json_str), dat) if v, ok := dat["ws"]; ok { ws := v.([]interface{}) for i, wsItem := range ws { wsMap := wsItem.(map[string]interface{}) if vCw, ok := wsMap["cw"]; ok { cw := vCw.([]interface{}) for i, cwItem := range cw { cwItemMap := cwItem.(map[string]interface{}) if w, ok := cwItemMap["w"]; ok { recResult = recResult + w.(string) } } } } } fmt.Println(recResult) }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
標(biāo)簽:銅川 重慶 雞西 欽州 蘭州 梅河口 吐魯番 汕頭
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Golang 實(shí)現(xiàn)interface類型轉(zhuǎn)string類型》,本文關(guān)鍵詞 Golang,實(shí)現(xiàn),interface,類型,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。