duanche4578 2015-12-05 09:08
浏览 38
已采纳

以数组开头的Golang解组json

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, "
")

    errTwo := json.NewDecoder(resp.Body).Decode(&re)
    if errTwo != nil {  fmt.Fprint(w, "Error decoding: ", errTwo, "
") }

    fmt.Fprint(w, "Response struct: ", re)
}
  • 写回答

2条回答 默认 最新

  • donglu6303 2015-12-05 11:14
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来