json - 使用 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"
}]
}]
}
除了不断循环遍历数据集并检查给定属性是否已添加到结构中之外,还有其他有效的方法吗?我的数据集没有排序,这使得通过循环控制添加变得更加困难。
解决方案
推荐阅读
- c++ - 具有两个碰撞对象的 C++ 控制台应用程序不起作用
- r - 永久保存 googleway API 密钥
- android - 动画相机在谷歌地图中定位和设置平移
- html - R 和 rvest:抓取 html 文件
- autodesk-forge - 无法添加核心扩展 Autodesk.InViewerSearch 分步教程 Autodesk Forge Viewer v2
- python - 查找python集合中的最大值
- symfony - 注意:未定义索引:在 Sonata admin 中添加多选时的父级
- javascript - ReactJS/TypeScript 从 Ajax 导出对象
- android - FragmentPagerAdapter 没有加载最后一个片段?
- javascript - 语法错误 - 当前未启用对实验性语法“decorators-legacy”的支持