登录
首页 >  Golang >  Go问答

将结构转换为扁平化的 json 的方法是什么?

来源:stackoverflow

时间:2024-02-14 11:09:24 409浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《将结构转换为扁平化的 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"
}

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


解决方案


最简单的方法(使用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
}

但是你可以看到,将结构标记更改为 person.age 可能不太优雅。

本篇关于《将结构转换为扁平化的 json 的方法是什么?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>