douxiangui5011 2016-10-10 16:00
浏览 246
已采纳

如何使用golang在JSON中填充并添加嵌套数组?

I am trying to learn how to create and manipulate JSON in this format on the fly using golang:

{ 
"justanarray": [ 
    "One", 
    "Two" 
], 
"nestedstring": {"name": {"first": "Dave"}}, 
"nestedarray": [ 
    {"address": {"street": "Central"}},  
    {"phone": {"cell": "(012)-345-6789"}}  
] 
} 

I can create and manipulate everything but the nested array.

Here is a play for the code below. 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("
I can set value of top level key that is an array.") 
        res2B.JustArray = []string{"One"} 
    MarshalIt(res2B)    

    fmt.Println("
I can append this top level array.") 
        res2B.JustArray = append(res2B.JustArray, "Two") 
    MarshalIt(res2B) 

    fmt.Println("
I can set value of a nested key.") 
        res2B.NestedString.Name.First = "Dave" 
        MarshalIt(res2B) 


    fmt.Println("
How in the heck do I populate, and append a nested array?") 


} 

func MarshalIt(res2B *JSONDoc){ 
        res, _ := json.Marshal(res2B) 
        fmt.Println(string(res)) 
}

Thanks for any help.

  • 写回答

1条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 关于#C++#2048游戏问题
      • ¥15 这种html怎么制作
      • ¥60 高仿微信的即时通讯app
      • ¥50 Window+VScode+opencv+tensorflow+anaconda实现行人检测与跟踪
      • ¥15 用AT89C51单片机汇编实现按键流水灯
      • ¥15 关于#matlab#的问题:偏微分方程降噪的程序,上面的迭代式的表达
      • ¥15 二叉树用二叉链存储问题
      • ¥15 VS2019不能设置QT的verson了,设置了点确定又消失了,怎么解决呢?
      • ¥15 用java解决,要解释一下给我
      • ¥100 项目经理想学开发牛牛指点迷津有偿