json.Marshal时特殊html字符被转义
在服务的一个接口开发时,发现日志中json的url某些符号被转义的情况,以此记录一下。
{
"imageId":"图片描述信息",
"imageUrl":"http://xxxx.xxxx/6d6de116c4c64c57933dd7d83940230220160525150701.jpg?imageView&thumbnail=750x750",
"url":"http://xxxx.xxx/6d6de116c4c64c57933dd7d83940230220160525150701.jpg",
"width":500,
"height":375,
}
在Go语言中,提供了json的编解码包,但是如果直接使用json.Marshal进行编码,在日志中看到是这样的,即&被转义成\u0026:
{
"imageId":"图片描述信息",
"imageUrl":"http://xxxx.xxxx/6d6de116c4c64c57933dd7d83940230220160525150701.jpg?imageView\u0026thumbnail=750x750",
"url":"http://xxxx.xxxx/6d6de116c4c64c57933dd7d83940230220160525150701.jpg",
"height":375,
"width":500
}
查看官方文档,发现json.Marshal默认会转义<>&这些特殊的HTML字符,官方也给出了解决办法,需要将json编码器设置为SetEscapeHTML(false)即可。
解决方法如下:
bt := bytes.NewBuffer([]byte{})
jsonEncoder := json.NewEncoder(bt)
jsonEncoder.SetEscapeHTML(false)
if err := jsonEncoder.Encode(response); err != nil {
// handle error
return
}