使用“嵌入式”密钥将JSON解组为结构

I have this JSON:

{
  id : "12345",
  videos: {
    results: [
      {
        id: "533ec655c3a3685448000505",
        key: "cYyx5DwWu0k"
      }
    ]
  }
}

And I want to unmarshal it to this struct:

type Film struct {
    ID          int     `json:"id"`
    Videos      []Video `json:"videos"`
}

type Video struct {
    ID   string  `json:"id"`
    Key  string  `json:"key"`
}

I mean, I want to Videos struct field to be videos.results array.

If I do this:

body := //retrieve json above
var film Film
json.Unmarshal(body, &film)

obviously doesn't work because it can't unmarshal videos json key to a Video array because of results key.

How can I do this?

You can define an unmarshaller for Film that "unpacks" the nested JSON structure for you. Example:

func (f *Film) UnmarshalJSON(b []byte) error {
    internal := struct {
        ID     int `json:"id"`
        Videos struct {
            Results []Video `json:"results"`
        } `json:"videos"`
    }{}

    if err := json.Unmarshal(b, &internal); err != nil {
        return err
    }
    f.ID = internal.ID
    f.Videos = internal.Videos.Results
    return nil
}

https://play.golang.org/p/rEiKqLYB-1