Home >Backend Development >Golang >How to Stop Go\'s JSON Marshaler from Converting \'&\' to \'&\'?

How to Stop Go\'s JSON Marshaler from Converting \'&\' to \'&\'?

DDD
DDDOriginal
2024-12-01 13:09:11994browse

How to Stop Go's JSON Marshaler from Converting '&' to '&'?

How to Prevent JSON from Converting '&' to '&'?

Problem Scenario

Consider the following code snippet:

package main</p>
<p>import (</p>
<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 '&'.

Solution

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>
<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!

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