golang json.Marshal 特殊html字符被轉(zhuǎn)義的解決方法
go語言提供了json的編解碼包,json字符串作為參數(shù)值傳輸時發(fā)現(xiàn),json.Marshal生成json特殊字符<、>、&會被轉(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,會轉(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)
這種方式比較直接,硬性字符串替換。比較憨厚
方法二:
文檔中寫到This escaping can be disabled using an Encoder that had SetEscapeHTML(false) alled on it.
我們先創(chuàng)建一個buffer用于存儲json
創(chuàng)建一個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
查看文檔和源碼還是解決問題的好方法。
以上這篇golang json.Marshal 特殊html字符被轉(zhuǎn)義的解決方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Golang中println和fmt.Println區(qū)別解析
Golang 中打印數(shù)據(jù)通常使用 fmt.Println() 方法,也可以使用內(nèi)置的 println() 方法。這兩個方法大家可能都使用過,它們的區(qū)別是什么呢?本文給大家詳細(xì)講解,感興趣的朋友跟隨小編一起看看吧2023-03-03
Go語言中TCP/IP網(wǎng)絡(luò)編程的深入講解
這篇文章主要給大家介紹了關(guān)于Go語言中TCP/IP網(wǎng)絡(luò)編程的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05
Go應(yīng)用中優(yōu)雅處理Error的技巧總結(jié)
在程序員中,尤其是go新手,經(jīng)常聽到的一個討論話題是:如何處理錯誤,這篇文章主要給大家介紹了關(guān)于Go應(yīng)用中優(yōu)雅處理Error的一些相關(guān)技巧,需要的朋友可以參考下2021-09-09

