Preventing JSON Escaping of "<" and ">" with json.Marshal
When using json.Marshal to convert a struct into JSON, special characters like "<" and ">" are automatically escaped to their Unicode equivalents. However, there may be cases where you want these characters to be preserved in their original form.
Problem Statement
Consider the following Go program:
package main import ( "encoding/json" "fmt" ) 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)) }
Output:
Before Marshal {<car><mirror>XML</mirror></car>} After marshal {"xmlRequest":"\u003ccar\u003e\u003cmirror\u003eXML\u003c/mirror\u003e\u003c/car\u003e"}
As you can see, the "<" and ">" characters have been escaped to "u003c" and "u003e" respectively.
Solution
As of Go 1.7, json.Marshal does not provide an option to disable HTML escaping. However, there is a workaround using a custom function:
func (t *Track) JSON() ([]byte, error) { buffer := &bytes.Buffer{} encoder := json.NewEncoder(buffer) encoder.SetEscapeHTML(false) err := encoder.Encode(t) return buffer.Bytes(), err }
By calling this function instead of json.Marshal, you can prevent the escaping of "<" and ">".
Output:
{"xmlRequest":"<car><mirror>XML</mirror></car>"}
The above is the detailed content of How to Prevent JSON Escaping of '' in Go's `json.Marshal`?. For more information, please follow other related articles on the PHP Chinese website!