在Golang中向嵌套的JSON添加条目。

huangapple go评论78阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年8月27日 06:13:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/45900081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定