【问题标题】:Golang how to send the correct JSON response message format?Golang 如何发送正确的 JSON 响应消息格式?
【发布时间】:2022-08-16 16:38:28
【问题描述】:

我有一个想要打印 JSON 响应消息的 golang 程序:

func MyPluginFunction(w http.ResponseWriter, r *http.Request){

  data := `{\"status\":\"false\",\"error\":\"bad request\"}`
  w.Header().Set(\"Content-Type\", \"application/json\")
  w.WriteHeader(http.StatusBadRequest )
  json.NewEncoder(w).Encode(data)

}

然而,当我使用这个函数时,我得到了一个奇怪的 JSON 格式的格式。它看起来像这样:

\"{\\\"status\\\":\\\"false\\\",\\\"error\\\":\\\"bad request\\\"}\"

有没有办法让响应消息变成普通的 JSON,比如:

{
  \"status\": \"false\",
  \"error\": \"bad request\"
}
  • 使用json.NewEncoder.Encode 编码字符串会将该字符串编码为有效的 JSON,无论其内容如何细绳.这就是您在输出中看到的内容。这是一个有效的 JSON细绳.要按原样发送data,请使用w.Write([]byte(data))
  • 或者使用 data 作为 json.RawMessage - pkg.go.dev/encoding/json#RawMessage

标签: go


【解决方案1】:

您的 data 已经包含 JSON 编码数据,因此您应该按原样编写它,而无需重新编码:

func MyPluginFunction(w http.ResponseWriter, r *http.Request) {
    data := `{"status":"false","error":"bad request"}`
    w.Header().Set("Content-Type", "application/json")
    if _, err := io.WriteString(w, data); err != nil {
        log.Printf("Error writing data: %v", err)
    }
}

如果您将data 传递给Encoder.Encode(),它将被视为“常规”字符串并将被编码,从而生成一个JSON 字符串,其中双引号根据JSON 规则进行转义。

【讨论】:

    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多