Sammy Roberts Sammy Roberts - 1 year ago 58
JSON Question

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

I have a struct

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

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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download