在Golang中将复杂的JSON结构初始化为地图

I need to provide a map[string]interface{} to a function. The JSON that is behind is this one :


{
   "update": {
     "comment": [
         {
            "add": {
               "body": "this is a body"
            }
         }
      ]
   }
}

I am completely stuck. I tried with nested structs, with maps, with a mix of both, I just cannot see the solution of this simple thing..

My last attempt is :

    // 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

I succeed with this, that I find quite ugly.

        // 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

Usually folks use interface{} and Unmarshal() for this!

Check out some examples

Hope this helps! :)

You could create and initialise json object using the following format.

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
", obj)
    obj2B, _ := json.Marshal(obj["buzz"])
    fmt.Println(string(obj2B))
}

Initialised object obj would be

map[buzz:{Update:{Comments:[{Add:{Body:foo}}]}}]

Try this code available here . For more detail, do refer this article