tommyd456 tommyd456 - 3 months ago 10
JSON Question

How to store object in a struct

I'm not sure how to create a

struct
to store a JSON object that is being posted to my API.

The JSON looks like this:

{
"name" : "Mr Robinson",
"email" : "test@test.com",
"username" : "robbo123",
"properties" : {
"property1" : "a property",
"property2" : "another property"
},
"permissions" : ["perm1", "perm2", "perm3"]
}


There can be any number of
properties
and the
permissions
array can contain any number of values.

I am using this to decode the posted values:

err := json.NewDecoder(req.Body).Decode(my_struct)


So far my struct looks like this:

type User struct {
Name string `json:"name"`
Email string `json:"email"`
Username string `json:"username"`
}

Answer

You can use a map[string]string for the properties and a []string slice for the permissions:

type User struct {
    Name        string            `json:"name"`
    Email       string            `json:"email"`
    Username    string            `json:"username"`
    Properties  map[string]string `json:"properties"`
    Permissions []string          `json:"permissions"`
}

Output (wrapped):

{Name:Mr Robinson Email:test@test.com Username:robbo123 
    Properties:map[property1:a property property2:another property]
    Permissions:[perm1 perm2 perm3]}

Try the complete runnable app on the Go Playground.

Comments