首页 > 解决方案 > 使用 Go 将平面数据转换为嵌套 JSON

问题描述

我试图找到一种有效的方法将平面数据从 DB 表转换为 Go 中的嵌套 JSON。

这是我将数据集加载到结构切片中的代码:

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

这将产生以下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"
}]

我希望能够将相同的数据集编码为:

type Globe struct {
    Name       string
    Hemisphere []Hemisphere
}

type Hemisphere struct {
    Name    string
    Country []Country
}

type Country struct {
    Name string
}

所以我可以编组 Globe 并以嵌套形式获取相同的数据集:

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

除了不断循环遍历数据集并检查给定属性是否已添加到结构中之外,还有其他有效的方法吗?我的数据集没有排序,这使得通过循环控制添加变得更加困难。

标签: jsongo

解决方案


推荐阅读