[英]How to send the correct JSON response message format
I have a Go program which I want to print the JSON response message:我有一个 Go 程序,我想打印 JSON 响应消息:
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)
}
However, when I used this function, I got a weird format in the JSON format.但是,当我使用这个 function 时,我得到了 JSON 格式的奇怪格式。 It looks like this:
它看起来像这样:
"{\"status\":\"false\",\"error\":\"bad request\"}"
Is there any way to make the response message becomes a normal JSON, like:有什么办法可以让响应消息变成正常的JSON,比如:
{
"status": "false",
"error": "bad request"
}
Your data
already contains JSON encoded data, so you should just write it as-is, without re-encoding it:您的
data
已经包含 JSON 编码数据,因此您应该按原样编写,无需重新编码:
func MyPluginFunction(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest )
data := `{"status":"false","error":"bad request"}`
if _, err := io.WriteString(w, data); err != nil {
log.Printf("Error writing data: %v", err)
}
}
If you pass data
to Encoder.Encode()
, it is treated as a "regular" string and will be encoded as such, resulting in a JSON string where double quotes are escaped as per JSON rules.如果您将
data
传递给Encoder.Encode()
,它将被视为“常规”字符串并将被编码,从而产生一个 JSON 字符串,其中双引号根据 JSON 规则进行转义。
You only have to JSON encode if you have a non-JSON Go value, such as in this example:如果您有非 JSON Go 值,则只需 JSON 编码,例如在此示例中:
func MyPluginFunction(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
data := map[string]any{
"status": "false",
"error": "bad request",
}
if err := json.NewEncoder(w).Encode(data); err != nil {
log.Printf("Error writing data: %v", err)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.