溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Go中json踩坑記錄的示例分析

發(fā)布時間:2021-06-15 11:58:07 來源:億速云 閱讀:224 作者:小新 欄目:編程語言

這篇文章主要介紹Go中json踩坑記錄的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

                       

JSON,一種輕量級的資料交換語言,該語言以易于讓人閱讀的文字為基礎,用來傳輸由屬性值或者序列性的值組成的數(shù)據對象?,F(xiàn)已經被廣泛應用,Go 當然也提供了完備的支持,通過 encoding/json 便可方便的序列化及反序列化 JSON 數(shù)據。但是也有些關鍵點需要額外注意下。

Go 可使用 json.Marshal() 便捷的獲取 JSON 數(shù)據,查看該函數(shù)對應的 godoc 文檔,里面有這么一段話:

String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. So that the JSON will be safe to embed inside HTML <script> tags, the string is encoded using HTMLEscape, which replaces "<", ">", "&", U+2028, and U+2029 are escaped to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". This replacement can be disabled when using an Encoder, by calling SetEscapeHTML(false).

json.Marshal() 在進行序列化時,會進行 HTMLEscape 編碼,會將 “<”, “>”, “&”, U+2028, 及 U+2029 轉碼成 “\u003c”,”\u003e”, “\u0026”, “\u2028”, 和 “\u2029”。這在正常使用時是沒有問題的,但如果在對接第三方需要對 JSON 字符串進行取摘要比對時,如果一方未進行 HTMLEscape 編碼,取出的摘要便會天差地別。上述文檔中也給出了解決方法,通過 SetEscapeHTML(false) 來禁用便可。方法如下:

bf := bytes.NewBuffer([]byte{})jsonEncoder := json.NewEncoder(bf)jsonEncoder.SetEscapeHTML(false)_ = jsonEncoder.Encode(body)jsonStr := bf.String()

但是這樣使用仍然會有些問題,json.Encoder.Encode() 會在 JSON 字符串后接一個 換行符,該函數(shù)源碼如下:

// Encode writes the JSON encoding of v to the stream,
// followed by a newline character.
//
// See the documentation for Marshal for details about the
// conversion of Go values to JSON.
func (enc *Encoder) Encode(v interface{}) error {
    if enc.err != nil {
        return enc.err
    }
    e := newEncodeState()
    err := e.marshal(v, encOpts{escapeHTML: enc.escapeHTML})
    if err != nil {
        return err
    }

    // Terminate each value with a newline.
    // This makes the output look a little nicer
    // when debugging, and some kind of space
    // is required if the encoded value was a number,
    // so that the reader knows there aren't more
    // digits coming.
    e.WriteByte('\n')

    b := e.Bytes()
    if enc.indentPrefix != "" || enc.indentValue != "" {
        if enc.indentBuf == nil {
            enc.indentBuf = new(bytes.Buffer)
        }
        enc.indentBuf.Reset()
        err = Indent(enc.indentBuf, b, enc.indentPrefix, enc.indentValue)
        if err != nil {
            return err
        }
        b = enc.indentBuf.Bytes()
    }
    if _, err = enc.w.Write(b); err != nil {
        enc.err = err
    }
    encodeStatePool.Put(e)
    return err
}

可以看出,該函數(shù)在進行序列化后又寫入了一個 \n 字符。如果不需要該字符,則需要額外的將其剔除:

jsonStr := string(bf.Bytes()[:bf.bf.Len()])

以上是“Go中json踩坑記錄的示例分析”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI