golang json.Marshal 特殊html字符被转义的解决方法
go语言提供了json的编解码包,json字符串作为参数值传输时发现,json.marshal生成json特殊字符<、>、&会被转义。
type test struct { content string } func main() { t := new(test) t.content = "http://www.baidu.com?id=123&test=1" jsonbyte, _ := json.marshal(t) fmt.println(string(jsonbyte)) }
{"content":"http://www.baidu.com?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 }
解决方案
方法一:
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 = "http://www.baidu.com?id=123&test=1" bf := bytes.newbuffer([]byte{}) jsonencoder := json.newencoder(bf) jsonencoder.setescapehtml(false) jsonencoder.encode(t) fmt.println(bf.string()) }
{"content":"http://www.baidu.com?id=123&test=1"} process finished with exit code 0
查看文档和源码还是解决问题的好方法。
以上这篇golang json.marshal 特殊html字符被转义的解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
上一篇: Go中recover与panic区别详解
下一篇: Vue加载json文件的方法简单示例