marcio
marcio

Reputation: 10512

How to represent this complex data structure with Go structs?

So I decided to give Go another chance but got stuck. Most Go struct examples in documentation are very simple and I found the following JSON object notation that I don't know how to represent with Go structs:

{
    id: 1,
    version: "1.0",
    method: "someString",
    params: [
        {
            clientid: "string",
            nickname: "string",
            level: "string"
        },
        [{
            value: "string",
            "function": "string"
        }]
    ]
}

How would you, more experienced gophers, represent that somewhat strange data in Go? And how to initialize the nested elements of the resulting struct?

Upvotes: 6

Views: 816

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65049

I would use a json.RawMessage slice for the params property.. then hide them behind an GetXXX method that decodes it all nicely. Somewhat like this:

type Outer struct {
    Id      int               `json:"id"`
    Version string            `json:"version"`
    Method  string            `json:"method"`
    Params  []json.RawMessage `json:"params"`
}

type Client struct {
    ClientId string `json:"clientid"`
    Nickname string `json:"nickname"`
    Level    string `json:"level"`
}

....

obj := Outer{}

err := json.Unmarshal([]byte(js), &obj)

if err != nil {
    fmt.Println(err)
}

fmt.Println(obj.Method) // prints "someString"

client := Client{}

err = json.Unmarshal(obj.Params[0], &client)

fmt.Println(client.Nickname) // prints "string"

Working (quickly smashed together at lunch time) sample: http://play.golang.org/p/Gp7UKj6pRK

That second param will need some input from you .. but you're basically looking at decoding it to a slice of whatever type you create to represent it.

Upvotes: 12

Related Questions