Consider the following code snippet:
package main</p> <p>import (</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">"encoding/json" "fmt" "log" "net/http"
)
func testFunc(w http.ResponseWriter, r *http.Request) {
data := make(map[string]string) data["key"] = "&" bytes, err := json.Marshal(data) if err != nil { fmt.Fprintln(w, "generator json error") } else { //print console fmt.Println(string(bytes)) fmt.Println("&") //print broswer fmt.Fprintln(w, string(bytes)) fmt.Fprintln(w, "&") }
}
func main() {
http.HandleFunc("/", testFunc) err := http.ListenAndServe(":9090", nil) if err != nil { log.Fatal("ListenAndServe", err) }
}
Upon executing this code, we notice that the ampersand character ('&') is being converted to & in both the browser and console output, despite its intended display as '&'.
In Go 1.7, a new option was introduced to address this issue:
func (*Encoder) SetEscapeHTML
This function allows us to disable the escaping of HTML entities, including '&', '<', and '>'.
To implement this solution in the example code, we modify the testFunc function as follows:
func testFunc(w http.ResponseWriter, r *http.Request) {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">... enc := json.NewEncoder(w) enc.SetEscapeHTML(false) ...
}
By disabling HTML escaping for the encoder, we ensure that the ampersand character is preserved as '&' in the JSON output, both in the browser and the console.
The above is the detailed content of How to Stop Go\'s JSON Marshaler from Converting \'&\' to \'&\'?. For more information, please follow other related articles on the PHP Chinese website!