iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > PHP编程 >Go语言 json.Marshal 转义html特殊字符(&、<、>)问题及解决
  • 741
分享到

Go语言 json.Marshal 转义html特殊字符(&、<、>)问题及解决

2024-04-02 19:04:59 741人浏览 安东尼
摘要

Go 语言解析生成 JSON 字符时,我们可以使用 json.Marshal() 来转换解析,但是如果生成的 JSON 字符串中含有特殊的字符如 <、> 和 & 时候那么他们将会被转义。 问题描述 type Test s

Go 语言解析生成 JSON 字符时,我们可以使用 json.Marshal() 来转换解析,但是如果生成的 JSON 字符串中含有特殊的字符如 <、> 和 & 时候那么他们将会被转义。

问题描述

type Test struct {
    Content     string
}
func main() {
    t := new(Test)
    t.Content = "https://www.baidu.com?q=1&page=1"
    jsonByte, _ := json.Marshal(t)
    fmt.Println(string(jsonByte))
}

输出结果如下,其中 & => \u0026

{"Content":"Https://www.baidu.com?q=1\u0026page=1"}

通过查询文档 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
}

解决方法

1.字符串替换

c = strings.Replace(c, "\\u003c", "<", -1)
c = strings.Replace(c, "\\u003e", ">", -1)
c = strings.Replace(c, "\\u0026", "&", -1)

这种方式干脆直接,但是批量的字符串替换。还是比较麻烦的。

2. 显示设置 SetEscapeHTML

文档中提到了: This escaping can be disabled using an Encoder that had SetEscapeHTML(false) alled on it.

我们可以通过创建 buffer 存储 json,再创建一个 jsonencoder 通过设置 SetEscapeHTML 编码为 false

type Test struct {
    Content     string
}
func main() {
    t := new(Test)
    t.Content = "https://www.baidu.com?id=1&page=1"
    bf := bytes.NewBuffer([]byte{})
    jsonEncoder := json.NewEncoder(bf)
    jsonEncoder.SetEscapeHTML(false)
    jsonEncoder.Encode(t)
    fmt.Println(bf.String())
}

输出结果:

{"Content":"https://www.baidu.com?id=1&page=1"}

--结束END--

本文标题: Go语言 json.Marshal 转义html特殊字符(&、<、>)问题及解决

本文链接: https://www.lsjlt.com/news/99255.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作