简体   繁体   中英

How do I include an array as part of a struct definition in 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM