下面由golang教程欄目給大家介紹golang解析json格式的方法,希望對需要的朋友有所幫助!
項(xiàng)目中客戶端和服務(wù)端的交互數(shù)據(jù)部分為json,因此在服務(wù)端就得解析,復(fù)雜的json解析起來其實(shí)還是挺費(fèi)勁的。
交互的數(shù)據(jù)類似如下格式:
{"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)行展示
- 從json數(shù)組中獲取ws
- ws是數(shù)組,數(shù)組元素為object
- cw是數(shù)組,數(shù)組元素為object
- w是string
- 從cw遍歷獲取w字段
初步實(shí)現(xiàn)如下:
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) }
這樣實(shí)現(xiàn),一層一層去轉(zhuǎn)換類型,再去獲取元素有點(diǎn)麻煩。既然是已知的json數(shù)據(jù)結(jié)構(gòu),那么可以定義好結(jié)構(gòu)體,再去進(jìn)行解析。
type CWItem struct { SC int32 `json:"sc"` W string `json:"w"`}type WSItem struct { CW []CWItem}type IatResult struct { SN int32 `json:"sn"` LS bool `json:"ls"` BG int32 `json:"bg"` ED int32 `json:"ed"` WS []WSItem `json:"ws"`}
注意定義的時(shí)候變量名第一個(gè)字母要大寫,也可以使用工具來自動(dòng)生成定義https://mholt.github.io/json-to-go/;用工具生成的挺漂亮:
type AutoGenerated struct { Sn int `json:"sn"` Ls bool `json:"ls"` Bg int `json:"bg"` Ed int `json:"ed"` Ws []struct { Bg int `json:"bg"` Cw []struct { Sc int `json:"sc"` W string `json:"w"` } `json:"cw"` } `json:"ws"` }
func RecResultJsonToPlain(jsonResult []byte)(recPlainResult string) { var r IatResult json.Unmarshal(jsonResult, &r) for _, wsItem := range r.WS { for _, cwItem := range wsItem.CW { recPlainResult = recPlainResult + cwItem.W } } return recPlainResult }
上面的元素有json:"sn"
強(qiáng)制說明,因此如果只需獲取對應(yīng)的元素,其他元素不定義也是可以的。另外還有一種數(shù)據(jù)就是數(shù)組當(dāng)中的元素還是數(shù)組,并且最后數(shù)組包含的是number或者string類型,需要再重寫一個(gè)函數(shù)才行,數(shù)據(jù)如下,獲取[21,1]當(dāng)中的元素
{"Asks": [[21, 1], [22, 1]] ,"Bids": [[20, 1], [19, 1]]}
搜索到一段代碼如下,重新實(shí)現(xiàn)了UnmarshalJSON
package mainimport ( "encoding/json" "fmt")type Message struct { Asks []Order `json:"Bids"` Bids []Order `json:"Asks"`}type Order struct { Price float64 Volume float64}func (o *Order) UnmarshalJSON(data []byte) error { var v [2]float64 if err := json.Unmarshal(data, &v); err != nil { return err } o.Price = v[0] o.Volume = v[1] return nil}func main() { b := []byte(`{"Asks": [[21, 1], [22, 1]] ,"Bids": [[20, 1], [19, 1]]}`) var m Message if err := json.Unmarshal(b, &m); err != nil { fmt.Println(err) return } fmt.Printf("%#vn", m)}