i've this template:
var ListTemplate = `
{
"resources": [
{{ StringsJoin . ", " }}
]
}
`
rendered with:
JoinFunc := template.FuncMap{"StringsJoin": strings.Join}
tmpl := template.Must(template.New("").Funcs(JoinFunc).Parse(ListTemplate))
if i send it to a http.ResponseWriter the output text is escaped.
var list []string
tmpl.Execute(w, list)
how can i write a json this way?
You shouldn't use Go's template engine (neither
text/template
norhtml/template
) to generate JSON output, as the template engine has no knowledge of JSON syntax and rules (escaping).Instead use the
encoding/json
package to generate JSON. You may usejson.Encoder
to write / stream the response directly to anio.Writer
, such ashttp.ResponseWriter
.Example:
Outputs (try it on the Go Playground):