问题:在golang中使用json.marshal时发现会出现>,&等HTML特殊字符被转义
这是由于使用json.marshal时默认escapeHTML为true导致。
//marshal 源码如下
func Marshal(v interface{}) ([]byte, error) {
e := newEncodeState()
err := e.marshal(v, encOpts{escapeHTML: true})
if err != nil {
return nil, err
}
buf := append([]byte(nil), e.Bytes()...)
encodeStatePool.Put(e)
return buf, nil
}
解决方案
str := "lily & lucy"
var bf bytes.Buffer
enc := json.NewEncoder(&bf)
enc.SetEscapeHTML(false)
enc.Encode(str)