1. 程式人生 > >golang json.Marshal 特殊html字元被轉義解決方案

golang json.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.

  1. 我們先建立一個buffer用於儲存json
  2. 建立一個jsonencoder
  3. 設定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

檢視文件和原始碼還是解決問題的好方法