How to represent Golang struct with variable field names

Viewed 177

If this has been answered somewhere else let me know but I couldn't find anything.

Basically, let's say we have the following JSON. string-id-001 can be an arbitrary string. We want to unmarshal it into a struct, and be able to access the unique id's.

{"list":{"string-id-001":{"id":"blah","name":"cool"},"string-id-002":{"id":"yas","name":"rad"}}}

Golang as far as I can tell would require something like below which doesn't work if the keyhere value is constantly changing. Eg if it's an ID

type Foo struct {
    List struct {
        StringID001 struct {
            ID   string `json:"id"`
            Name string `json:"name"`
        } `json:"string-id-001"`
        StringID002 struct {
            ID   string `json:"id"`
            Name string `json:"name"`
        } `json:"string-id-002"`
    } `json:"list"`
}

I've seen a similar issue in another project (which I solved with interfaces rather than structs), and I'm wondering if there's a nicer solution. Am I missing something obvious?

1 Answers

type payLoad struct {
     ID   string `json:"id"`
     Name string `json:"name"`
}

type Foo struct {
    List map[string]payLoad `json:"list"`
}

Related