golangjson.Marshal特殊html字符被转义的解决⽅法go语⾔提供了json的编解码包,json字符串作为参数值传输时发现,json.Marshal⽣成json特殊字符<、>、&会被转义。type Test struct {
Content  string
}
func main() {
t := new(Test)
t.Content = "www.baidu?id=123&test=1"
jsonByte, _ := json.Marshal(t)
fmt.Println(string(jsonByte))
}
{"Content":"www.baidu?id=123\u0026test=1"}
Process finished with exit code 0
GoDoc描述
String values encode as JSON strings coerced to valid UTF-8,
replacing invalid bytes with the Unicode replacement rune.
The angle brackets “<” and “>” are escaped to “\u003c” and “\u003e”
to keep some browsers from misinterpreting JSON output as HTML.
Ampersand “&” is also escaped to “\u0026” for the same reason.
This escaping can be disabled using an Encoder that had SetEscapeHTML(false) alled on it.
json.Marshal 默认 escapeHtml 为true,会转义 <、>、&
func Marshal(v interface{}) ([]byte, error) {
e := &encodeState{}
err := e.marshal(v, encOpts{escapeHTML: true})
if err != nil {
return nil, err
}
return e.Bytes(), nil
}pdf转html
解决⽅案
⽅法⼀:
content = strings.Replace(content, "\\u003c", "<", -1)
content = strings.Replace(content, "\\u003e", ">", -1)
content = strings.Replace(content, "\\u0026", "&", -1)
这种⽅式⽐较直接,硬性字符串替换。⽐较憨厚
⽅法⼆:
⽂档中写到This escaping can be disabled using an Encoder that had SetEscapeHTML(false) alled on it.
我们先创建⼀个buffer⽤于存储json
创建⼀个jsonencoder
设置html编码为false
type Test struct {
Content  string
}
func main() {
t := new(Test)
t.Content = "www.baidu?id=123&test=1"
bf := bytes.NewBuffer([]byte{})
jsonEncoder := json.NewEncoder(bf)
jsonEncoder.SetEscapeHTML(false)
jsonEncoder.Encode(t)
fmt.Println(bf.String())
}
{"Content":"www.baidu?id=123&test=1"}
Process finished with exit code 0
查看⽂档和源码还是解决问题的好⽅法。
以上这篇golang json.Marshal 特殊html字符被转义的解决⽅法就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。