您不应该使用Go的模板引擎(也不
text/template是
html/template)来生成JSON输出,因为模板引擎不了解JSON语法和规则(转义)。
而是使用
encoding/json包来生成JSON。您可以用来
json.Enprer直接将响应写入/流式传输到
io.Writer,例如
http.ResponseWriter。
例:
type Output struct { Resources []string `json:"resources"`}obj := Output{ Resources: []string{"r1", "r2"},}enc := json.NewEnprer(w)if err := enc.Enpre(obj); err != nil { // Handle error fmt.Println(err)}输出(在Go Playground上尝试):
{"resources":["r1","r2"]}


