资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

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.

我们先创建一个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字符被转义的解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持创新互联。


分享标题:golangjson.Marshal特殊html字符被转义的解决方法
链接URL:http://cdkjz.cn/article/igppoo.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220