I'm trying to return a simple json in Go. This is a web app and here's a part of a handler:
func JsonTest1(w http.ResponseWriter, r *http.Request) {
test1 := "something1"
test2 := 456
j1 := []byte(fmt.Sprintf(`
{
data: {
"test1": %s,
"test2": %d
}
}
`, test1, test2))
j2, _ := json.Marshal(&j1)
w.Header().Set("Content-Type", "application/json")
w.Write(j2)
}
When I'm doing a request via curl, I receive something like:
CiAgICB7CiAgICAgIGRhdGE6IHsKICAgICAgICAicmVkaXJlY3RfdXJsIjogdGVzdF9yZWRpcl91cmwxLAogICAgICAgICJtZXNzYWdlIjogdGVzdCBtc2cgMQogICAgICB9CiAgICB9CiAg
Why? How to fix that?
When you JSON-encode a []byte
, it will be rendered as a base64-encoded string, the most effective way to represent an arbitrary byte slice/array in JSON (the only real alternative being "field": [7, 129, 13, 48, ...]
and so on). In your code, however, you're doing a couple of unusual things that may not be what's intended:
Sprintf
, then trying to JSON-encode your JSON. json.Marshal
is for taking some arbitrary Go value and rendering it as JSON.What you want is probably one of these options:
// Manually-created *valid* JSON
func JsonTest1(w http.ResponseWriter, r *http.Request) {
test1 := "something1"
test2 := 456
// %q instead of %s gives us a quoted string:
j1 := []byte(fmt.Sprintf(`
{
data: {
"test1": %q,
"test2": %d
}
}
`, test1, test2))
w.Header().Set("Content-Type", "application/json")
w.Write(j1)
}
// JSON created with json.Marshal
func JsonTest2(w http.ResponseWriter, r *http.Request) {
test1 := "something1"
test2 := 456
data := map[string]interface{}{
"data": map[string]interface{}{
"test1": test1,
"test2": test2,
},
}
j1, _ := json.Marshal(data)
w.Header().Set("Content-Type", "application/json")
w.Write(j1)
}