Home > Backend Development > Golang > How to Prevent JSON Responses from Displaying ASCII Codes Instead of Characters?

How to Prevent JSON Responses from Displaying ASCII Codes Instead of Characters?

Patricia Arquette
Release: 2024-11-28 15:22:10
Original
427 people have browsed it

How to Prevent JSON Responses from Displaying ASCII Codes Instead of Characters?

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)
Copy after login

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.")
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template