英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论