[英]How do I populate and append a nested array in JSON using golang?
我正在尝试学习如何使用 golang 动态创建和操作这种格式的 JSON:
{
"justanarray": [
"One",
"Two"
],
"nestedstring": {"name": {"first": "Dave"}},
"nestedarray": [
{"address": {"street": "Central"}},
{"phone": {"cell": "(012)-345-6789"}}
]
}
我可以创建和操作除嵌套数组之外的所有内容。
这是下面代码的播放。 https://play.golang.org/p/pxKX4IOE8v
package main
import (
"fmt"
"encoding/json"
)
//############ Define Structs ################
//Top level of json doc
type JSONDoc struct {
JustArray []string `json:"justanarray"`
NestedString NestedString `json:"nestedstring"`
NestedArray []NestedArray `json:"nestedarray"`
}
//nested string
type NestedString struct {
Name Name `json:"name"`
}
type Name struct {
First string `json:"first"`
}
//Nested array
type NestedArray []struct {
Address Address `json:"address,omitempty"`
Phone Phone `json:"phone,omitempty"`
}
type Address struct {
Street string `json:"street"`
}
type Phone struct {
Cell string `json:"cell"`
}
func main() {
res2B := &JSONDoc{}
fmt.Println("I can create a skeleton json doc")
MarshalIt(res2B)
fmt.Println("\nI can set value of top level key that is an array.")
res2B.JustArray = []string{"One"}
MarshalIt(res2B)
fmt.Println("\nI can append this top level array.")
res2B.JustArray = append(res2B.JustArray, "Two")
MarshalIt(res2B)
fmt.Println("\nI can set value of a nested key.")
res2B.NestedString.Name.First = "Dave"
MarshalIt(res2B)
fmt.Println("\nHow in the heck do I populate, and append a nested array?")
}
func MarshalIt(res2B *JSONDoc){
res, _ := json.Marshal(res2B)
fmt.Println(string(res))
}
谢谢你的帮助。
与其将NestedArray
定义为匿名结构的切片,不如在JSONDoc
重新定义它,如下所示:
type JSONDoc struct {
JustArray []string `json:"justanarray"`
NestedString NestedString `json:"nestedstring"`
NestedArray []NestedArrayElem `json:"nestedarray"`
}
//Nested array
type NestedArrayElem struct {
Address Address `json:"address,omitempty"`
Phone Phone `json:"phone,omitempty"`
}
然后,你可以这样做:
res2B := &JSONDoc{}
res2B.NestedArray = []NestedArrayElem{
{Address: Address{Street: "foo"}},
{Phone: Phone{Cell: "bar"}},
}
MarshalIt(res2B)
游乐场: https : //play.golang.org/p/_euwT-TEWp 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.