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

发布时间:2022-04-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了golang json.Marshal 特殊html字符被转义的解决方法脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

go语言提供了json的编解码包,json字符串作为参数值传输时发现,json.Marshal生成json特殊字符<、>、&amp;会被转义。

tyPE test struct {
  Content   string
}
func main() {
  t := new(Test)
  t.Content = "http://www.baidu.COM&#63;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.

我们先创建一个buffer用于存储json

创建一个jsonencoder

设置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

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

以上这篇golang json.Marshal 特殊html字符被转义的解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本宝典。

脚本宝典总结

以上是脚本宝典为你收集整理的golang json.Marshal 特殊html字符被转义的解决方法全部内容,希望文章能够帮你解决golang json.Marshal 特殊html字符被转义的解决方法所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。