如何发送正确的JSON响应消息格式

huangapple go评论79阅读模式
英文:

How to send the correct JSON response message format

问题

我有一个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)
}

然而,当我使用这个函数时,JSON格式的输出变得很奇怪。它看起来像这样:

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

有没有办法让响应消息变成一个正常的JSON,像这样:

{
  "status": "false",
  "error": "bad request"
}
英文:

I have a Go program which I want to print the JSON response message:

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. It looks like this:

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

Is there any way to make the response message becomes a normal JSON, like:

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

答案1

得分: 6

你的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)
    }
}

如果你将data传递给Encoder.Encode(),它会被视为一个“普通”的字符串,并按照JSON规则进行编码,结果是一个JSON字符串,其中双引号被转义。

只有当你有一个非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]interface{}{
        "status": "false",
        "error":  "bad request",
    }
    if err := json.NewEncoder(w).Encode(data); err != nil {
        log.Printf("Error writing data: %v", err)
    }
}
英文:

Your data already contains JSON encoded data, so you should just write it as-is, without re-encoding it:

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.

You only have to JSON encode if you have a non-JSON Go value, such as in this example:

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)
	}
}

huangapple
  • 本文由 发表于 2022年8月16日 16:35:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/73371078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定