Convert request body content to anonymous struct that i can access attributes

473 views
Skip to first unread message

Paulo Coutinho

unread,
Aug 13, 2015, 11:04:27 PM8/13/15
to golang-nuts
Hi,

I want convert the body of request to an anonymous struct or something that i can access the attributes.

My current code:

func (s *CustomerController) customerAdd(c *gin.Context) {
decoder := json.NewDecoder(c.Request.Body)
var t interface{}
err := decoder.Decode(&t)
if err != nil {
log.Println("PAM! > ")
log.Println(err)
} else {
log.Println("JSON CONV: ")
log.Println(t)
}
}

But it is the object converted:

JSON CONV: 

map[field3:map[field4:field 4 value] field5:1 field1:fiel 1 value field2:fiel áéíóú value]


Can anyone help me?


My json:


{

    "field1": "fiel 1 value",

    "field2": "fiel áéíóú value",

    "field3": {

        "field4": "field 4 value"

    },

    "field5": 1

}


I need access the data of my object (t). 

Thanks.

Paulo Coutinho

unread,
Aug 13, 2015, 11:06:21 PM8/13/15
to golang-nuts
I get the field now, but need change the type of "t":

func (s *CustomerController) customerAdd(c *gin.Context) {
decoder := json.NewDecoder(c.Request.Body)
   var t map[string]interface{}

err := decoder.Decode(&t)
if err != nil {
log.Println("PAM! > ")
log.Println(err)
} else {
log.Println("JSON CONV: ")
log.Println(t)
      log.Println("VALUE: ")
log.Println(t["field1"])
}
}


This is a good way?

Tamás Gulácsi

unread,
Aug 14, 2015, 2:22:26 AM8/14/15
to golang-nuts
Acceptable, if you don't know the keys beforehand. Or define a struct for the known keys and unmarshal into that.

Hari Haran

unread,
Aug 14, 2015, 9:43:50 AM8/14/15
to golang-nuts
If the JSON is complicated, you can get the struct definition automatically using https://mholt.github.io/json-to-go/ . You can decode into that struct and access the fields.
Reply all
Reply to author
Forward
0 new messages