Home > Net >  How to send the correct JSON response message format
How to send the correct JSON response message format

Time:08-16

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

CodePudding user response:

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