How to Display Characters Instead of ASCII in JSON Responses
In this programming question, a user is experiencing an issue where JSON data containing an ampersand "&" is being displayed with its ASCII code "u0026" instead of the actual character.
Resolving the Issue:
The provided solution involves utilizing a feature introduced in Go1.7. By disabling HTML escaping in the JSON encoder, the ampersand character can be preserved as it is in the JSON data.
Implementation Using Encoder.DisableHTMLEscaping:
To disable HTML escaping, use the Encoder.DisableHTMLEscaping method. This method sets the EscapeHTML field of the encoder to false, effectively disabling the escaping of HTML characters.
encoder := json.NewEncoder(responseWriter) encoder.SetEscapeHTML(false)
By modifying the code with this method, the HTTP server will now display the ampersand character without any ASCII conversion. Here is the modified version of the testFunc function:
func testFunc(w http.ResponseWriter, r *http.Request) { data := make(map[string]string) data["key"] = "&" encoder := json.NewEncoder(w) encoder.SetEscapeHTML(false) if err := encoder.Encode(data); err != nil { fmt.Fprintln(w, "Failed to generate JSON.") } }
Now, both the browser and console will display the ampersand character as intended, without any ASCII conversion.
The above is the detailed content of How to Prevent JSON Responses from Displaying ASCII Codes Instead of Characters?. For more information, please follow other related articles on the PHP Chinese website!