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
でそれを再定義する方が良いでしょう
おかげAinar-Gが、これは "nestedarray" の構造を有するように見える:[ { "アドレス":{ "通り": "FOO"}、 "電話":{ "セル": " "} }、 { "アドレス":{" 通り ": ""}、 "電話":{" セル ": "バー"} } ]' – sneeze
Ainar-G、おかげで再び、私がありましたインターフェースを使ってあなたの答えを少し変えることができます。あなたの助けを借りて私は解決策に近いと信じています。私のパズルの最後の部分はこれです。どのように追加するのですか?おかげさまで、ありがとうございます。 – sneeze
@sneezeここではインターフェイスは必要ありませんが、ポインタで十分です。また、追加するときは、スライスではなく値を使用する必要があります。 https://play.golang.org/p/hs4SGHSn7Q –