英文:
Adding entries to nested json in Golang
问题
我需要在Go语言中创建一个嵌套的JSON对象。然后,在运行时向内部对象添加值,而这些值将是不同的类型。这就是为什么我初始化了一个interface{}。
i := map[string]interface{}{"name":"name"}
t := map[string]interface{}{"internal":internal_map}
if somestuff != ""{
template_map["internal"]["somestuff"] = somestuff
}
if somestuff2 != true{
template_map["internal"]["somestuff2"] = somestuff2
}
上面的代码无法运行,因为会出现type interface {} does not support indexing
错误。
我需要同时满足三个条件:嵌套的JSON、不同的类型和内部对象的运行时构建。
英文:
I need to create a nested JSON in Go. Then, on runtime, append values into inner object, and those values will be of different types. This is why I initiate a interface{}.
i := map[string]interface{}{"name":"name"}
t := map[string]interface{}{"internal":internal_map}
if somestuff != ""{
template_map["internal"]["somestuff"] = somestuff
}
if somestuff2 != true{
template_map["internal"]["somestuff2"] = somestuff2
}
Now, the code above does not run due to type interface {} does not support indexing
error.
I need all 3 - nested JSON, different types and run-time construction of internal object.
答案1
得分: 0
将第二行改为
t := map[string]map[string]interface{}{"internal": internal_map}
可以像这样访问它 t["internal"]["key_in_internal_map"]
。
这本质上是一个嵌套的映射。你可以添加任意多层的嵌套。
Goplayground 示例。尽管我建议使用嵌套结构体来避免映射链。
英文:
Change line number two to
t := map[string]map[string]interface{}{"internal":internal_map}
Access it like this t["internal"]["key_in_internal_map"]
.
This is essentially a map of maps. You can add as many embedded levels as you want.
Goplayground example.
Although I would recommend making nested structs to avoid map chaining.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论