Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert interface{} to struct in Golang

I am very new to Go and am trying to get my head around all the different types and how to use them. I have an interface with the following (which was originally in a json file):

[map[item:electricity transform:{fuelType}] map[transform:{fuelType} item:gas]]

and I have the following struct

type urlTransform struct {
        item string
        transform string
}

I have no idea how to get the interface data into the struct; I'm sure this is really stupid, but I have been trying all day. Any help would be greatly appreciated.

like image 948
Paul A.T. Wilson Avatar asked Mar 24 '17 18:03

Paul A.T. Wilson


2 Answers

Decode the JSON directly to types you want instead of decoding to an interface{}.

Declare types that match the structure of your JSON data. Use structs for JSON objects and slices for JSON arrays:

type transform struct {
    // not enough information in question to fill this in.
}

type urlTransform struct {
    Item string
    Transform transform
}

var transforms []urlTransform

The field names must be exported (start with uppercase letter).

Unmarshal the JSON to the declared value:

err := json.Unmarshal(data, &transforms)

or

err := json.NewDecoder(reader).Decode(&transforms)
like image 122
Bayta Darell Avatar answered Sep 21 '22 09:09

Bayta Darell


From your response : [map[item:electricity transform:{fuelType}] map[transform:{fuelType} item:gas]]. As you can see here this is a an array that has map in it.

One way to get the value from this is :

values := yourResponse[0].(map[string]interface{}). // convert first index to map that has interface value.
transform := urlTransform{}
transform.Item = values["item"].(string) // convert the item value to string
transform.Transform = values["transform"].(string)
//and so on...

as you can see from the code above I'm getting the the value using map. And convert the value to the appropriate type in this case is string.

You can convert it to appropriate type like int or bool or other type. but this approach is painful as you need to get the value one bye one and assign it your your field struct.

like image 44
Gujarat Santana Avatar answered Sep 17 '22 09:09

Gujarat Santana