您好,登錄后才能下訂單哦!
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字符被轉義的解決方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。