具有未知属性名称的结构的嵌套属性? [英] Nested properties for structs with unknown property names?

查看:40
本文介绍了具有未知属性名称的结构的嵌套属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON从外部源将一些值转换为变量.

I'm using JSON to get some values into a variable from an external source.

我的类型是 json.Unmarshal 将值放入:

I have a type like this that json.Unmarshal puts values into:

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

    var data Frame

解组后,我可以通过以下方式访问类型: data.Type

After unmarshal, I can access a the type by: data.Type

但是,如果我尝试执行以下操作:

but if I try doing something like:

    if data.Type == "image" {
        fmt.Printf("%s\n", data.Value.Imagedata)
    }

编译器抱怨没有这样的值 data.Value.Imagedata .

The compiler complains about no such value data.Value.Imagedata.

所以我的问题是,如何根据某些条件引用我知道会存在的Go属性?

So my question is, how do I reference properties in Go that I know will be there depending on some condition?

做到这一点:

    type Image struct {
        Filename string
    }

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

但这不是很灵活,因为我将收到不同的 Value s.

But that isn't very flexible as I will be receiving different Values.

推荐答案

json.Unmarshal 会尽力将数据放置在与您的类型最匹配的位置.从技术上讲,您的第一个示例可以使用,但是您尝试使用点表示法访问 Value 字段,即使您声明它是地图也是如此:

json.Unmarshal will do its best to place the data where it best aligns with your type. Technically your first example will work, but you are trying to access the Value field with dot notation, even though you declared it to be a map:

这应该为您提供某种形式的输出:

This should give you some form of output:

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

...考虑到"Imagedata"是JSON中的键.

… considering that "Imagedata" was a key in the JSON.

您可以选择根据需要或期望的结构深度定义类型,或者使用 interface {} 然后对值进行类型声明.将 Value 字段作为映射,您将始终访问诸如 Value [key] 之类的键,并且该映射项的值是 interface {} ,您可以输入断言,例如 Value [key].(float64).

You have the option of defining the type as deeply as you want or expect the structure to be, or using an interface{} and then doing type assertions on the values. With the Value field being a map, you would always access the keys like Value[key], and the value of that map entry is an interface{} which you could type assert like Value[key].(float64).

关于执行更明确的结构,我发现您可以将对象分解为自己的类型,也可以将其嵌套在一个位置:

As for doing more explicit structures, I have found that you could either break up the objects into their own types, or define it nested in one place:

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

单独的结构

type Frame struct {
    Type    string
    Value   value 
}

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

我仍在学习自己,所以这是我目前的理解程度:-).

I'm still learning Go myself, so this the extent of my current understanding :-).

这篇关于具有未知属性名称的结构的嵌套属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆