How to unmarshal multi dimensional array inside struct

I have following data:-

{"me":[{"id": "0xcfd","Title":"Story of Stackoverflow","Users":[{"id":"1","Name":"MetaBoss"},{"id":"2","Name":"Owner"}],"Tag":"golang,programming"}]}

and I have the following struct:-

type Root struct {
    ID string `json:"id,omitempty"`
    Title string `json:"Title,omitempty"`
    Myuser Users `json:"Users,omitempty"` // Users is struct
    Tag string `json:"Tag,omitempty"`
}

type Users struct {
    ID string `json:"id,omitempty"`
    Name string `json:"Name,omitempty"`
}

To unmarshal the data, I am trying to do following things -

type Unmarh struct {
    Me []Root `json:"me"`
}

var r Unmarh
err = json.Unmarshal(response, &r)

while printing r.Me[0].Myuser, I am not able to get data.

I am getting below error -

json: cannot unmarshal array into go struct field Root.Myuser of type User struct {....Users struct data}

It needs Myuser to be multidimensional array type and not Users struct. I have no Idea, how to represent Users multidimensional array inside struct

1 answer

  • answered 2018-05-16 06:09 mkopriva

    In the json the Users key is an array and so the corresponding Go field should be a slice.

    type Root struct {
        ID    string `json:"id,omitempty"`
        Title string `json:"Title,omitempty"`
        Users []User `json:"Users,omitempty"`
        Tag   string `json:"Tag,omitempty"`
    }
    

    https://play.golang.org/p/azE7kPFs02V