4 回答

TA貢獻1887條經驗 獲得超5個贊
您可以使用以下格式創建并初始化 json 對象。
import (
? ?"fmt",
? ?"encoding/json"
)
type Object struct {
? ? ?Update Update `json:"update"`
}
type Update struct {
? ? Comments []Comment `json:"comments"`
}
type Comment struct {
? ? Add Add `json:"add"`
}
type Add struct {
? ? Body Body `json:"body"`
}
type Body string
func main() {
? ? obj := make(map[string]Object)
? ? obj["buzz"] = Object{
? ? ? ? Update: Update{
? ? ? ? ? ? Comments: []Comment{
? ? ? ? ? ? ? ? Comment{
? ? ? ? ? ? ? ? ? ? Add: Add{
? ? ? ? ? ? ? ? ? ? ? ? ?Body: "foo",
? ? ? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? },
? ? ? ? ? ? },
? ? ? ? },
? ? }
? ? fmt.Printf("%+v\n", obj)
? ? obj2B, _ := json.Marshal(obj["buzz"])
? ? fmt.Println(string(obj2B))
}
初始化對象 obj 將是
map[buzz:{Update:{Comments:[{Add:{Body:foo}}]}}]

TA貢獻1828條經驗 獲得超13個贊
可能晚了3年,但我自己也偶然發現了這個問題,顯然你也可以這樣做:
data := map[string]interface{}{
"update": map[string]interface{}{
"comment": []map[string]interface{}{
{
"add": map[string]string{
"body": "this is a body",
},
},
},
},
}

TA貢獻1797條經驗 獲得超6個贊
我成功了,我覺得這很丑。
// Prepare the data
var data = make(map[string]interface{})
var comments []map[string]map[string]string
var comment = make(map[string]map[string]string)
comment["add"] = map[string]string{
"body": "Test",
}
comments = append(comments, comment)
var update = make(map[string]interface{})
update["comment"] = comments
data["update"] = update
- 4 回答
- 0 關注
- 317 瀏覽
添加回答
舉報