Home >Backend Development >Golang >How Can I Encode Characters in JSON Without ASCII Escaping in Go?
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.
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.
Go1.7 introduced the SetEscapeHTML method, which accepts a boolean parameter. When set to false, HTML escaping is disabled for the Encoder.
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!