dongpiao8821 2015-06-24 20:26
浏览 43
已采纳

如何将地图嵌入结构中,使其具有平面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 }

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/)

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,
        },
    }
}

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

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?

  • 写回答

2条回答 默认 最新

  • duanbamo0127 2015-06-24 20:43
    关注

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

    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{}

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题