Home >Backend Development >Golang >How to Display an Ampersand (&) Unescaped in Go\'s JSON Response?

How to Display an Ampersand (&) Unescaped in Go\'s JSON Response?

Linda Hamilton
Linda HamiltonOriginal
2024-12-03 09:40:10416browse

How to Display an Ampersand (&) Unescaped in Go's JSON Response?

Handling Character Display Instead of ASCII

In the provided Go code, the goal is to display an ampersand character (&) in a JSON response. However, the current code results in the ampersand being escaped as "u0026".

To address this, we need to disable HTML escaping in the JSON encoder. In Go versions prior to 1.7, this was not possible. However, Go 1.7 introduced a new option: Encoder.DisableHTMLEscaping.

This option allows us to prevent the escaping of <, >, and & characters in JSON strings. To use this option, we need to set it on the encoder object.

enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)

Once the HTML escaping is disabled, the encoder will no longer escape the ampersand character, resulting in the desired output:

Chrome browser show:

{
    "key": "&"
}
&

Console also show:

{
    "key": "&"
}
&

The above is the detailed content of How to Display an Ampersand (&) Unescaped in Go\'s JSON Response?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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