golang json.Marshal 特殊 html 字符被转义解决方案

本贴最后更新于 2186 天前,其中的信息可能已经事过景迁

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.

  1. 我们先创建一个 buffer 用于存储 json
  2. 创建一个 jsonencoder
  3. 设置 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

查看文档和源码还是解决问题的好方法

  • JSON

    JSON (JavaScript Object Notation)是一种轻量级的数据交换格式。易于人类阅读和编写。同时也易于机器解析和生成。

    51 引用 • 190 回帖 • 2 关注
  • golang

    Go 语言是 Google 推出的一种全新的编程语言,可以在不损失应用程序性能的情况下降低代码的复杂性。谷歌首席软件工程师罗布派克(Rob Pike)说:我们之所以开发 Go,是因为过去 10 多年间软件开发的难度令人沮丧。Go 是谷歌 2009 发布的第二款编程语言。

    491 引用 • 1383 回帖 • 374 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...