Sammy Roberts Sammy Roberts - 2 months ago 9
JSON Question

How to deal with Struct having different json key than json response

I have a struct

VideoInfo
that has a key in it called
embedCode
. The API I am querying returns the embed code as
embed_code
. During unmarshalling the response how do I ensure
embed_code
goes into
embedCode
?

Also is there an easy way to take a large json string and automatically turn it into a struct, or can one only use a map?

Answer

With respect to remapping the field names use the corresponding annotation in the structure declaration:

type VideoInfo struct {
    EmbedCode string `json:"embed_code"`
}

The marshaller/un-marshaller will only process public field, so you need to capitalise the field name.

With respect to converting the whole structure, yes it is easy. Declare an instance to un-marshal into and pass a reference to the json.Unmarshal method (from a test):

data, _ := json.Marshal(request)

var resp response.VideoInfo
if err := json.Unmarshal(data, &resp); err != nil {
    t.Errorf("unexpected error, %v", err)
}