Traveller Traveller - 5 months ago 17
JSON Question

json.Marshal behaves differently with two objects (Go/Golang)

So i want to marshal data to JSON. The basic struct looks like this:

type DatabaseObject struct {
Preferences []int `json:"preferences"`
Texts map[string]string `json:"texts"`
Options map[string]string `json:"options"`
Gender string `json:"gender"`
EMail string `json:"email"`
}


Here is the (working) Playground version: https://play.golang.org/p/GI3nAo7L4a

When i use this code in my program however, the result is very different. Here is my code:

jsonObject, err := json.Marshal(DatabaseObject{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", jsonObject)


It prints:

[123 34 112 114 101 102 101 114 101 110 99 101 115 34 58 110 117 108 108 44 34 116 101 120 116 115 34 58 110 117 108 108 44 34 111 112 116 105 111 110 115 34 58 110 117 108 108 44 34 103 101 110 100 101 114 34 58 34 34 44 34 101 109 97 105 108 34 58 34 34 125]


Does anyone know why json.Marshal does not work here? It's an empty struct, it should look like this

{"preferences":null,"texts":null,"options":null,"gender":"","email":""}

Answer

You're trying to print the representation of what json.Marshal outputs with %+v.

json.Marshal returns a byte slice which is exactly what you're looking at.

jsonObject, err := json.Marshal(DatabaseObject{})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("%+v", jsonObject)

Will print the bytes for the JSON string. If instead you use fmt.Printf("%s", jsonObject) you'll get what you're looking for.

Another option would be fmt.Printf("%+v", string(jsonObject)) just so you can see what I'm talking about I've modified the playground you provided. https://play.golang.org/p/ipbSbryk1L