首页 > 解决方案 > 如何将结构保存为扁平化的 json?

问题描述

type Profile struct {
    Personal struct {
        Age int `json:"age"`
        Address string `json:"address"`
    } `json:"personal"`

    Education struct {
         Bachelor string `json:"bs"`
         Master string `json:"ms"`
    } `json:"education"`
}

json.Marshal产生类似的json

{
    "personal": { "age": 40, "address": "ABC" },
    "education" : { "bs": "AAA", "ms" :"BBB"}
}

我怎样才能创建一个扁平的json,比如

{
    "personal.age" : 40, "personal.address",
    "education.bs" : "AAA", "education.ms" : "BBB"
}

我搜索了一些帖子,但除了展平地图外找不到任何其他内容。

标签: go

解决方案


最简单的方法(使用encoding/json):

type Personal struct {
        Age     int    `json:"personal.age"`
        Address string `json:"personal.address"`
}

type Education struct {
        Bachelor string `json:"education.bs"`
        Master   string `json:"education.ms"`
}

type Profile struct {
        Personal
        Education
}

但是您可以看到,将 struct 标签更改为person.age.


推荐阅读