Golang解析以数组开头的JSON。

huangapple go评论93阅读模式
英文:

Golang unmarshal json that starts as an array

问题

我正在尝试解析这个JSON https://www.reddit.com/r/videos/comments/3vgdsb/recruitment_2016.json

它起始于两个不同对象的数组,我只需要第二个对象的数据。

我想要获取评论的内容,当我尝试解码时没有出现任何错误,但它没有捕获到我想要的数据。

这是我运行后得到的输出:

// 初始化时的 Response 结构体: []
// 解码后的 Response 结构体: [{{{[]}}} {{{[]}}}]

以下是代码部分:

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)
}
英文:

I'm trying to unmarshal this json https://www.reddit.com/r/videos/comments/3vgdsb/recruitment_2016.json

It starts as an array of two different objects, and I only need data on the second object.

I want to retrieve the comments body, it doesn't give me any error when i'm trying to decode it, but it doesn't capture the data I want.

This is the output I get from running this:

//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)
}

答案1

得分: 8

对于所有在创建正确的JSON解组结构方面遇到困难的人,这里有一个很棒的网站,可以将任何JSON转换为正确的Go结构:JSON-to-Go

英文:

For everyone that is struggling to create the right structure for JSON unmarshalling, here's a cool website that convert any JSON to the right Go struct: JSON-to-Go

答案2

得分: 3

你正在解析的 JSON 数据与你的数据不符合,如果字段的名称与你的结构体不一样,你应该使用结构体标签。应该更像这样:

type Response []struct {
    Kind string `json:"kind"`
    Data struct {
        Children []struct {
            Data struct {
                Replies []struct {
                    // whatever...
                } `json:"replies"`
            } `json:"data"`
        } `json:"children"`
    } `json:"data"`
}

当然,我会用真实的命名类型替换内联类型,但我只是在这里强调数据层次结构。

该 JSON 真是丑陋而臃肿。

英文:

The json data you are unmarshaling does not conform with your data, and if the names of the fields are not like in your struct, you should use struct tags as well. It should be more like this:

type Response []struct {
        Kind string `json:"kind"`
        Data struct {
            Children []struct {
                Data struct {
                    Replies []struct {
                       // whatever...
                    } `json:"replies"`
                } `json:"data"`
            } `json:"children"`
        } `json:"data"`
    }
}

Of course I'd replace the inline types with real, named types, but I'm just making a point here in regards to the data hierarchy.

Goddamn, that's some ugly bloated JSON BTW.

huangapple
  • 本文由 发表于 2015年12月5日 17:08:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/34103157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定