Home >Backend Development >Golang >How Can I Encode Characters in JSON Without ASCII Escaping in Go?

How Can I Encode Characters in JSON Without ASCII Escaping in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 15:29:10178browse

How Can I Encode Characters in JSON Without ASCII Escaping in Go?

Encoding Characters in JSON Without ASCII Escaping

In this instance, the goal is to display a character in JSON without ASCII escaping. Using Go1.7, the Encoder.DisableHTMLEscaping option offers a solution.

Escaping in JSON

Typically, characters like <, >, and & are escaped in JSON with sequences like u003C. However, if these characters are intended to appear in their original form, escaping needs to be disabled.

The SetEscapeHTML Method

Go1.7 introduced the SetEscapeHTML method, which accepts a boolean parameter. When set to false, HTML escaping is disabled for the Encoder.

Implementation Example

The following code demonstrates how to utilize the SetEscapeHTML method to disable HTML escaping:

import "encoding/json"

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

    // Encode a map with an '&' character
    err := enc.Encode(map[string]string{
        "key": "&",
    })
    if err != nil {
        panic(err)
    }
}

By disabling HTML escaping, the '&' character will be preserved in the JSON output, achieving the desired result.

The above is the detailed content of How Can I Encode Characters in JSON Without ASCII Escaping in Go?. 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