[英]Golang unmarshal json that starts as an array
我正在嘗試解組此json https://www.reddit.com/r/videos/comments/3vgdsb/recruitment_2016.json
它以兩個不同對象的數組開始,我只需要第二個對象上的數據。
我想檢索注釋正文,當我嘗試對其進行解碼時,它不會給我任何錯誤,但它不會捕獲我想要的數據。
這是我從運行此命令得到的輸出:
//Response struct when initialized: []
//Response struct decoded: [{{{[]}}} {{{[]}}}]
////
type Response []struct {
Parent struct {
Data struct {
Children []struct {
Com Comment
}
}
}
}
type Comment struct {
Name string `json:"body"`
}
func init() {
http.HandleFunc("/api/getcomments", getComments)
}
func getComments(w http.ResponseWriter, r *http.Request) {
url := "https://www.reddit.com/r/videos/comments/3vgdsb/recruitment_2016.json"
c := appengine.NewContext(r)
client := urlfetch.Client(c)
resp, err := client.Get(url)
if err != nil { fmt.Fprint(w, "Error client.Get(): ", err) }
re := new(Response)
fmt.Fprint(w, "Response struct: ", re, "\n")
errTwo := json.NewDecoder(resp.Body).Decode(&re)
if errTwo != nil { fmt.Fprint(w, "Error decoding: ", errTwo, "\n") }
fmt.Fprint(w, "Response struct: ", re)
}
對於每個努力為JSON解組創建正確的結構的人來說,這是一個很酷的網站,可以將任何JSON轉換為正確的Go結構: JSON-to-Go
您要解組的json數據與您的數據不一致,並且如果字段名稱與struct中的字段名稱不同,則也應使用struct標記。 應該更像這樣:
type Response []struct {
Kind string `json:"kind"`
Data struct {
Children []struct {
Data struct {
Replies []struct {
// whatever...
} `json:"replies"`
} `json:"data"`
} `json:"children"`
} `json:"data"`
}
}
當然,我將用真正的命名類型替換內聯類型,但是在這里我只是想說明數據層次結構。
該死的,這是丑陋的,blo腫的JSON BTW。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.