2016-10-10 11 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)) 
} 

任意の助けてくれてありがとう。代わりに、匿名構造体のスライスとしてNestedArrayを定義するので、それはのようなJSONDocでそれを再定義する方が良いでしょう

答えて

1

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、おかげで再び、私がありましたインターフェースを使ってあなたの答えを少し変えることができます。あなたの助けを借りて私は解決策に近いと信じています。私のパズルの最後の部分はこれです。どのように追加するのですか?おかげさまで、ありがとうございます。 – sneeze

+1

@sneezeここではインターフェイスは必要ありませんが、ポインタで十分です。また、追加するときは、スライスではなく値を使用する必要があります。 https://play.golang.org/p/hs4SGHSn7Q –

関連する問題