golang: encoding/json包关于&<>字符的转义
版本环境:
$ go version
go version go1.13.6 windows/amd64
示例代码:
package main
import (
"encoding/json"
"log"
)
func main() {
object := struct {
Value string
}{
Value:"test1280&<>",
}
if result, err := json.Marshal(object); err == nil {
log.Print(string(result))
} else {
log.Fatal(err)
}
}
运行输出:
$ go run main.go
2020/09/27 18:22:29 {"Value":"test1280\u0026\u003c\u003e"}
我们预期的是{“Value”:“test1280&<>”},输出与预期不相符合。
异常原因:
golang标准包encoding/json 默认地 将&<>这三个字符进行转义。
其实JSON规范中并没有要求将&<>作为特殊字符转义处理,仅仅是encoding/json自己的行为。
官网说明:
https://golang.org/pkg/encoding/json/
String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. So that the JSON will be safe to embed inside HTML <script> tags, the string is encoded using HTMLEscape, which replaces “<”, “>”, “&”, U+2028, and U+2029 are escaped to “\u003c”,"\u003e", “\u0026”, “\u2028”, and “\u2029”. This replacement can be disabled when using an Encoder, by calling SetEscapeHTML(false).
which replaces “<”, “>”, “&”, U+2028, and U+2029 are escaped to “\u003c”,"\u003e", “\u0026”, “\u2028”, and “\u2029”
解决办法:
可以参考golang官网提供的接口来 关闭默认开启的转义行为开关 :
https://golang.org/pkg/encoding/json/#Encoder.SetEscapeHTML
Code:
package main
import (
"bytes"
"encoding/json"
"log"
)
func main() {
object := struct {
Value string
}{
Value:"test1280&<>",
}
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(object)
if err != nil {
log.Fatal(err)
}
log.Print(string(buffer.Bytes())) // log.Print(buffer.String())
}
运行输出:
$ go run main.go
2020/09/27 21:56:03 {"Value":"test1280&<>"}
Value的值包含&<>并且没有被转义。
参考资料:
1.https://blog.csdn.net/lgh1700/article/details/104522878
2.https://blog.csdn.net/weixin_38707040/article/details/103664391
3.https://blog.csdn.net/naruto227/article/details/103810101
4.https://blog.csdn.net/liuhui251435428/article/details/102905213