本文介绍了如何将地图嵌入到结构中,以使其具有平坦的json表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了创建类似表格的结构,我在以前的应用程序中以以下格式序列化了行数据:

In order to create a table-like structure, I serialized my row data in following format in my previous application:

{ "key1": "...", "key2": "...", "15/04": 1.3, "15/05": 1.2, .... "17/08": 0.8 }

现在,我正在尝试用Go重写它,以便通过动手实践来学习该语言.在Go中,可以将两个结构嵌入到另一个结构中,从而将它们组合在一起.从该结构中封送的json将具有一个平面结构,即生成的json对象将具有第一和第二个结构的字段的并集而不嵌套.这是一个示例: https://play.golang.org/p/jbJykip7pw (摘自 http://attilaolah.eu/2014/09 /10/json-and-struct-composition-in-go/)

Now I am trying to rewrite it in Go in order to learn the language with hands-on experience. In Go, one can compose two structs together by embedding them into another struct. The marshalled json out of that struct will have a flat structure, i.e. the resulting json object will have union of fields of first and second structs without nesting. Here is an example: https://play.golang.org/p/jbJykip7pw (from http://attilaolah.eu/2014/09/10/json-and-struct-composition-in-go/)

我猜我也可以将地图嵌入结构中,以便可以使用以下类型定义在json上进行编组:

I guessed I could also embed a map into a struct so that I can marshall above json using following type definitions:

type Row struct {
    key1 string
    key2 string
    RowData
}

type RowData map[string]float64

...
func main() {
    row := Row{
        "...",
        "...",
        RowData{
            "15/04": 1.3, "15/05": 1.2, .... "17/08": 0.8,
        },
    }
}

但这会在我的行"对象中创建一个字段行数据"字段,而不是将行数据中的条目附加到所需的平面json对象中:

But this created a field 'RowData' field in my 'Row' object, instead of appending entries in the RowData into my desired flat json object:

{ "key1": "...", "key2": "...", "RowData": { "15/04": 1.3, "15/05": 1.2, .... "17/08": 0.8 } }

我想知道,是否有一种方法可以将地图或切片嵌入到结构中,从而使得生成的json对象是平坦的,而无需在类型Row上定义MarshalJSON函数?

I would like to know, if there is a way to embed maps or slices into a struct so that resulting json object is flat, without defining a MarshalJSON function on type Row?

推荐答案

简短的回答是否".该语言不允许您将任何类型(切片或映射)嵌入结构中.

The short answer is no. The language does not allow you to embed either type (slice or map) in a struct.

只需使用map[string]interface{}.处理以下事实:"key1"和"key2"的值是字符串,而其他所有值在其他地方都是浮点数.这确实是获得该输出的唯一方法.您可以使问题变得更复杂(例如将其转换为更像您的类型的东西),但是如果您不愿意实现MarshalJSON,那么唯一会产生所需结果的模型就是

Just use a map[string]interface{}. Deal with the fact that the values for "key1" and "key2" are strings and everything else is a float somewhere else. That's really the only way you're getting that output. You can make the problem as complicated as you'd like beyond this (like transform into a type more like yours or something) but if you're averse to implementing MarshalJSON the only model which will produce the results you want is map[string]interface{}

这篇关于如何将地图嵌入到结构中,以使其具有平坦的json表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:51