json - 在 Golang 中初始化和插入嵌套的 JSON 数据?
问题描述
在过去的 3 个小时里,我一直在努力尝试让它工作,所以希望你们能够帮助我解决这个问题。
我正在尝试在 Go 中初始化嵌套的 JSON 结构并将数据插入其中。这是我要处理的 JSON 的结构:
{
"top": {
"item1": {
"foo": "bar"
},
"item2": "This is item2",
"item3": "This is item3",
"item4": {
"foo2": "bar2"
}
}
}
这就是我在 Go 中设置它的方式——
package main
import (
"fmt"
)
func main() {
data := make(map[string]map[string]map[string]string) // init top level map
data["top"] = make(map[string]map[string]string)
data["top"]["item1"] = make(map[string]string)
data["top"]["item4"] = make(map[string]string)
data["top"]["item1"]["foo"] = "bar"
data["top"]["item4"]["foo2"] = "bar2"
data["top"]["item2"] = "This is item2"
fmt.Println(data)
}
但是,如果我运行它,我会收到此错误:
不能在赋值中使用“This is item2”(类型字符串)作为类型 map[string]string
我确定我让这变得过于复杂,那么表达这一点的更有效方式是什么?
解决方案
使用嵌套映射可能会有点混乱,因此使用结构可能有助于使您的数据结构更易于管理。
考虑使用json-to-go 之类的工具来帮助您为 JSON 数据构建适当的对象。
注意: 这不会每次都提供完美的结构 - 事实上,当它无法识别正确的类型时,这个工具通常会默认使用接口类型(这并不理想),因此您可能需要自定义输出,但总体而言,它将为您提供一个良好的起点。
操场上的工作示例
推荐阅读
- r - 为什么有些 R 包无法安装
- html - 鼠标悬停在表格的偶数行上时,盒子阴影不可见
- html - Angular mat-list-option 文本未换行
- javascript - 使用 javascript 正则表达式匹配验证输入文本字段
- angular - TypeError:无法读取未定义的属性“hasAttached”
- wordpress - 如何将自定义字段添加到菜单管理后端页面(wordpress)
- vba - 如何遍历共享邮件收件箱文件夹的子文件夹的子文件夹?
- nanoframework - Nanoframework 网络服务器下载/上传文件
- ios - 添加 Passbase 时未构建 Flutter 应用程序
- python - 如果调试退出,则执行 pytest 夹具拆卸