亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Golang 中將復雜的 JSON 結構初始化為映射

在 Golang 中將復雜的 JSON 結構初始化為映射

Go
慕桂英3389331 2023-06-26 18:08:55
我需要提供map[string]interface{}一個函數。后面的 JSON 是這樣的:{   "update": {     "comment": [         {            "add": {               "body": "this is a body"            }         }      ]   }}我完全被困住了。我嘗試使用嵌套結構、地圖、兩者的混合,我只是看不到這個簡單問題的解決方案。我的最后一次嘗試是:    // 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)    data["update"]["comment"] = comments
查看完整描述

4 回答

?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

通常人們使用interface{}andUnmarshal()來達到這個目的!

查看完整回答
反對 回復 2023-06-26
?
慕工程0101907

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}}]}}]

查看完整回答
反對 回復 2023-06-26
?
慕田峪7331174

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",

                },

            },

        },

    },

}


查看完整回答
反對 回復 2023-06-26
?
互換的青春

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


查看完整回答
反對 回復 2023-06-26
  • 4 回答
  • 0 關注
  • 317 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號