1

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
fallais
  • 577
  • 1
  • 8
  • 32

4 Answers4

2

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

Check out some examples

Hope this helps! :)

ladygremlin
  • 452
  • 3
  • 14
1

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

codenio
  • 721
  • 10
  • 17
  • You could create a new map of type `map[string]Object` and assign the initialised `obj` var to it. – codenio Jul 04 '19 at 10:56
0

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
fallais
  • 577
  • 1
  • 8
  • 32
0

Might be 3 years late, but also stumbled upon this problem myself, apparently you could also do something like this:

data := map[string]interface{}{
    "update": map[string]interface{}{
        "comment": []map[string]interface{}{
            {
                "add": map[string]string{
                    "body": "this is a body",
                },
            },
        },
    },
}
Julienn
  • 189
  • 1
  • 3
  • 11