2016-10-10 106 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 –