Converting an interface {} to a structure in the Golang

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

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

and I have the following structure

type urlTransform struct {
        item string
        transform string
}

I do not know how to get the interface data in the structure; I'm sure this is really stupid, but I tried all day. Any help would be greatly appreciated.

+4
source share
2 answers

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

Declare types that match the structure of your JSON data. Use structures for objects and JSON fragments 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

exported ( ).

JSON :

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

err := json.NewDecoder(reader).Decode(&transforms)
+4

: [map[item:electricity transform:{fuelType}] map[transform:{fuelType} item:gas]]. , array, map.

:

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...

, . - string.

int bool . , .

+2

Source: https://habr.com/ru/post/1673151/


All Articles