dsfdsf21312 2014-07-23 19:43
浏览 53
已采纳

如何在GO中将数组作为结构定义的一部分包含在内?

I am trying to parse a relatively complex bit of JSON. It has direct nodes, and it has arrays that have a variable number of elements. Here is a sample:

{
status: 200,
generated: "2014-07-23T13:09:30.315Z",
copyright: "Copyright (c) 2014 Us Not You. All Rights Reserved.",
results: 1,
start: 0,
links: {
        next: null,
        prev: null,
        self: "http://thing.com/thing.json"
    },
docs: [
        {
            id: "thingID_001",
        }
    ]
}

Simplified, of course. There may be zero or more docs each of which has a number of nodes. "links" is easy, I define a struct with the correct fields and there we go. But docs, I cannot get to marshal. Here is my code:

import (
    "net/http"
    "fmt"
    "io/ioutil"
    "encoding/json"
)
type Thinglinks struct {
    Next string
    Prev string
    Self string
}
//type ThingDoc struct {
//    Id string
//   Type string
//}
type ThingSection struct {
    Status int
    Generated string
    Copyright string
    Results int
    Start int
    Links thinglinks
    Docs []map[string]interface{}
}

func main() {
    resp, err := http.Get("http://thing.com/thing.json")
    if err != nil {
        fmt.Println(err)
        }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    var s ThingSection
    err3 := json.Unmarshal(body, &s)
    if err3 == nil {
        fmt.Println(s)
        fmt.Println(s.Links.Self)
        if len(s.Docs) >0 {
            fmt.Println(s.Docs[0])
        }
    } else {
        fmt.Println(err3)
    }
}

When I compile and run I get my expected results for all the nodes except Docs, which is always an empty set.

I strongly suspect that it is the "Docs" definition in the type declaration for the ThingSection struct, but I haven't been able to figure out what to do there.

Any assistance?

  • 写回答

1条回答 默认 最新

  • douke6857 2014-07-23 20:06
    关注

    If that is your actual JSON you will have issues. JSON needs quotes around field names as seen in the language definition here: http://json.org/ and you may not have extraneous commas.

    I have this bit on the playground and it works for me just fine after adding the quotes and removing the extraneous ',' inside the docs.

    http://play.golang.org/p/6OYeTuftfg

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!