doudizhu2222 2019-03-11 15:55
浏览 54

使用Go将平面数据转换为嵌套JSON

I'm trying to find an efficient way to convert flat data from a DB table into a nested JSON in Go.

This is my code to load my dataset into a slice of structs:

https://play.golang.org/p/_80nASVgds-

Which will produce the following json:

[{
    "Globe": "World",
    "Hemisphere": "Northern",
    "Country": "USA"
}, {
    "Globe": "World",
    "Hemisphere": "Southern",
    "Country": "Australia"
}, {
    "Globe": "World",
    "Hemisphere": "Southern",
    "Country": "Brazil"
}, {
    "Globe": "World",
    "Hemisphere": "Southern",
    "Country": "South Africa"
}, {
    "Globe": "World",
    "Hemisphere": "Northern",
    "Country": "Spain"
}]

I'd like to be able to be able to encode the same dataset into something like:

type Globe struct {
    Name       string
    Hemisphere []Hemisphere
}

type Hemisphere struct {
    Name    string
    Country []Country
}

type Country struct {
    Name string
}

So I could marshal Globe and get the same dataset in a nested form as such:

https://play.golang.org/p/r9OlCw_EwSA

{
    "Name": "World",
    "Hemisphere": [{
        "Name": "Northern",
        "Country": [{
            "Name": "USA"
        }, {
            "Name": "Spain"
        }]
    }, {
        "Name": "Southern",
        "Country": [{
            "Name": "Australia"
        }, {
            "Name": "South Africa"
        }, {
            "Name": "Brazil"
        }]
    }]
}

Is there any effective way of doing this other than looping through the dataset constantly and checking if a given property has already been added into the struct? My dataset is not ordered which makes it even more difficult to control the additions through loops.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 软件测试决策法疑问求解答
    • ¥15 win11 23H2删除推荐的项目,支持注册表等
    • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
    • ¥15 qt6.6.3 基于百度云的语音识别 不会改
    • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
    • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
    • ¥15 lingo18勾选global solver求解使用的算法
    • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行