我正在尝试找到一种有效的方法,可以将数据库表中的平面数据转换为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"
}]
}]
}
除了不断循环遍历数据集并检查给定属性是否已添加到结构中之外,还有其他有效的方法吗?我的数据集没有排序,这使得通过循环控制添加项更加困难。