2016-10-10 37 views
1

我想學習如何創建和使用golang在飛這種格式操縱JSON:如何使用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)) 
} 

感謝您的任何幫助。

回答

1

而不是定義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

+0

由於Ainar-G,但這似乎具有的 「nestedarray」 以下結構: { 「地址」:{ 「街道」: 「foo」 的}, 「電話」:{ 「細胞」:「 「} }, { 」地址「:{」 街頭 「: 」「}, 」手機「:{」 細胞「: 」酒吧「} } ]' – sneeze

+0

Ainar-G,再次感謝,我是能夠使用界面修改您的答案,並且在您的幫助下,我相信我已經接近解決方案。對我來說最後一件難題就是這個。我如何追加? https://play.golang.org/p/0i0t8O_KrN謝謝! – sneeze

+1

@sneeze你不需要接口,指針就足夠了。另外,當你追加時,你應該使用一個值,而不是一個片。 https://play.golang.org/p/hs4SGHSn7Q –