Go 解析嵌套 json
写项目的时候,请求了一个接口,发现返回的json数据,多层嵌套的,而且嵌套的第二层data是数组,第三层的news也是数组
所以需要写多个嵌套json进行解析,使用json.Unmarshal 进行嵌套结构体的解析
json截图为:
代码实例:
package main import ( "encoding/json" "io/ioutil" "net/http" "net/url" "fmt" ) type HotNews struct { Code int `json:"code"` Status string `json:"status"` Msg string `json:"msg"` Data []Datas `json:"data"` } type Datas struct { Symbol string `json:"symbol"` Hot int `json:"hot"` News []NewsInfo `json:"news"` } type NewsInfo struct { Symbol string `json:"symbol"` News_id string `json:"news_id"` Hot string `json:"hot"` Url string `json:"url"` Title string `json:"title"` Pv string `json:"pv"` Pub_time string `json:"pub_time"` Source string `json:"source"` } func getData(urlApi string) (body []byte,err error) { apiUrl :=urlApi u,err := url.ParseRequestURI(apiUrl) if err !=nil{ fmt.Println("request url failed err:",err) return nil,err } //u.RawQuery = data.Encode() fmt.Println(u.String()) resp,err := http.Get(u.String()) if err !=nil{ fmt.Println("get url failed err :",err) return nil,err } defer resp.Body.Close() body,err = ioutil.ReadAll(resp.Body) if err !=nil{ fmt.Println("read body failed err :",err) return nil,err } return body,nil } func main() { var hn HotNews urlApi := "https://xxx/hot" body,err := getData(urlApi) if err !=nil{ fmt.Println("get data failed err:",err) return } err = json.Unmarshal(body,&hn) if err !=nil{ fmt.Println("unmarshal failed err:",err) return } fmt.Println(hn.Code) fmt.Println(hn.Data) for _,v:= range hn.Data{ for _,n := range v.News{ fmt.Println(n.Source) } } }