Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent this complex data structure with Go structs?

Tags:

json

struct

go

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?

like image 481
marcio Avatar asked Nov 28 '14 03:11

marcio


1 Answers

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.

like image 187
Simon Whitehead Avatar answered Sep 25 '22 08:09

Simon Whitehead