How do I include an array as part of a struct definition in GO?

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

How do I include an array as part of a struct definition in GO?

问题

我正在尝试解析一个相对复杂的JSON数据。它包含直接的节点和包含可变数量元素的数组。这是一个示例:

{
"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"
}
]
}

当然,这只是一个简化的示例。可能会有零个或多个docs,每个docs都有多个节点。"links"很容易处理,只需定义一个具有正确字段的结构体即可。但是docs部分,我无法进行编组。这是我的代码:

import (
"net/http"
"fmt"
"io/ioutil"
"encoding/json"
)

type ThingLinks struct {
Next string
Prev string
Self 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)
}
}

当我编译和运行时,我得到了我期望的结果,除了Docs部分总是为空集。

我强烈怀疑问题出在ThingSection结构体的"Docs"定义上,但我还没有找到解决方法。

请帮忙看看。

英文:

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

得分: 5

如果这是你实际的JSON,你将会遇到问题。JSON需要在字段名称周围加上引号,就像在这里的语言定义中所看到的:http://json.org/,而且你可能没有多余的逗号。

我在playground上测试了这段代码,在我添加了引号并删除了文档中多余的逗号后,它对我来说完全正常。

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

英文:

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

huangapple
  • 本文由 发表于 2014年7月24日 03:43:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/24919539.html
匿名

发表评论

匿名网友

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

确定