GoLang: Nested properties for structures with unknown property names?

I use json to get some values ​​in the structure from an external source. Using UnMarshal to place values ​​in a structure.

I have such a structure that UnMarshal puts values ​​in:

type Frame struct{ Type string Value map[string]interface{} } var data Frame 

After UnMarshal, I can access by type: data.Type

but if I try to do something like:

 if data.Type == 'image'{ fmt.Println(fmt.Sprintf("%s", data.Value.Imagedata)) } 

The compiler does not complain about the value of data.Value.Imagedata

So my question is: how do I refer to properties in GoLang in code that I know will be there, depending on some condition?

Doing this job:

 type Image struct{ Filename string } type Frame struct{ Type string Value map[string]interface{} } 

But this is not very flexible as I get different Value s

+9
struct go
Mar 21 2018-12-12T00:
source share
1 answer

UnMarshal will do its best to accommodate the data that best aligns with your structure. Technically, your first example will work, but you are trying to access the Value field with dotted notation, even if you stated that it is a map:

This should give you some form of output:

 if data.Type == 'image'{ fmt.Printf("%v\n", data.Value["Imagedata"]) } 

... given that "Imagedata" is the key to json.

You have the option to define the structure as deep as you want, or expect the structure to be, or use the {} interface, and then make type statements for the values. When the Value field is a map, you will always access keys such as Value[key] , and then the value of this map is the {} interface, which you can enter assert, for example Value[key].(float64)

Regarding the implementation of more explicit structures, I found that you can either split the objects into your own structures, or define it nested in one place:

Nested (with anonymous structure)

 type Frame struct { Type string Value struct { Imagedata string `json:"image_data"` } } 

Separate structures

 type Frame struct { Type string Value value } type value struct { Imagedata string `json:"image_data"` } 

I am still participating. Go it yourself, so this is my understanding :-)

+14
Mar 21 '12 at 9:05
source share



All Articles