c json html转义字符,Go语言 json.Marshal 转义html特殊字符(&、<、>)问题及解决 - sdk社区 | 技术至上...

本文探讨了Go语言中使用json.Marshal()时遇到的特殊字符转义问题,并提供了两种解决方案:一是通过字符串替换来手动调整转义后的字符;二是通过json.Encoder设置SetEscapeHTML(false)来禁用HTML转义。

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 “” 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", "

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"}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值