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

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看