How to embed a map into a struct so that it has a flat json representation

一曲冷凌霜 提交于 2019-12-05 21:17:28

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

I know there is an accepted answer already but actually you can get the specified "desired flat json object."

"RowData" is not exactly a map[string]float; getting it's type will yield "main.RowData" (if this is in package main). And it can be embedded in a struct. Take this example, adapted from the original post:

package main

import (

    "encoding/json"
    "fmt"
)

type Row struct {
    Key1 string
    Key2 string
    RowData
}

type RowData map[string]float64

func main() {
    row := Row{
        RowData: make(map[string]float64),
    }
    row.RowData["15/04"] = 1.3
    row.RowData["15/05"] = 1.2
    row.RowData["17/08"] = 0.8
    row.Key1 = "value one"
    row.Key2 = "value two"

    flatJSON, _ := json.Marshal(row)
    fmt.Println(string(flatJSON))
}

That will yield:

{"Key1":"value one","Key2":"value two","RowData":{"15/04":1.3,"15/05":1.2,"17/08":0.8}}

The field names will have to be capitals in order to be exported but you can make them match the exact string specified in the question using struct tags.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!