欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

golang json.Marshal 特殊html字符被轉(zhuǎn)義的解決方法

 更新時(shí)間:2019年08月26日 09:44:36   作者:李浩的life  
今天小編就為大家分享一篇golang json.Marshal 特殊html字符被轉(zhuǎn)義的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

go語(yǔ)言提供了json的編解碼包,json字符串作為參數(shù)值傳輸時(shí)發(fā)現(xiàn),json.Marshal生成json特殊字符<、>、&會(huì)被轉(zhuǎn)義。

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 默認(rèn) escapeHtml 為true,會(huì)轉(zhuǎn)義 <、>、&

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)

這種方式比較直接,硬性字符串替換。比較憨厚

方法二:

文檔中寫(xiě)到This escaping can be disabled using an Encoder that had SetEscapeHTML(false) alled on it.

我們先創(chuàng)建一個(gè)buffer用于存儲(chǔ)json

創(chuàng)建一個(gè)jsonencoder

設(shè)置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

查看文檔和源碼還是解決問(wèn)題的好方法。

以上這篇golang json.Marshal 特殊html字符被轉(zhuǎn)義的解決方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論