In Go, the json.Marshal function automatically escapes angle brackets (<, >) and ampersands (&) in strings. However, this can be undesirable in certain situations.
Consider the following example:
package main import ( "fmt" "encoding/json" ) type Track struct { XmlRequest string `json:"xmlRequest"` } func main() { message := new(Track) message.XmlRequest = "<car><mirror>XML</mirror></car>" fmt.Println("Before Marshal", message) messageJSON, _ := json.Marshal(message) fmt.Println("After marshal", string(messageJSON)) }
This code will print the following output:
Before Marshal {xmlRequest:<car><mirror>XML</mirror></car>} After marshal {"xmlRequest":"\u003ccar\u003e\u003cmirror\u003eXML\u003c/mirror\u003e\u003c/car\u003e"}
Notice that the angle brackets and ampersand in the XML request string are escaped in the JSON output.
Prior to Go 1.7, it was impossible to prevent json.Marshal from escaping these characters. However, now there is a workaround:
func (t *Track) JSON() ([]byte, error) { buffer := &bytes.Buffer{} encoder := json.NewEncoder(buffer) encoder.SetEscapeHTML(false) err := encoder.Encode(t) return buffer.Bytes(), err }
This function first creates a byte buffer and a JSON encoder. Then, it sets the EscapeHTML option to false to prevent the encoder from escaping HTML characters, including angle brackets and ampersands.
If you want to apply this solution to your own custom type, modify the JSON() function as follows:
func JSONMarshal(t interface{}) ([]byte, error) { buffer := &bytes.Buffer{} encoder := json.NewEncoder(buffer) encoder.SetEscapeHTML(false) err := encoder.Encode(t) return buffer.Bytes(), err }
Now, you can use JSONMarshal to marshal any custom type and prevent the escaping of angle brackets and ampersands.
The above is the detailed content of How to Prevent JSON Marshal from Escaping Angle Brackets and Ampersands in Go?. For more information, please follow other related articles on the PHP Chinese website!