ホームページ  >  記事  >  バックエンド開発  >  Go json トラップ レコードを共有する

Go json トラップ レコードを共有する

藏色散人
藏色散人転載
2021-06-15 11:05:232162ブラウズ

以下は、golang チュートリアル コラムからの Go json トラップ レコードです。困っている友人に役立つことを願っています。

JSONは、読みやすいテキストに基づいており、属性値またはシリアル値で構成されるデータオブジェクトを送信するために使用されます。もちろん、Go も完全にサポートしており、encoding/json を通じて JSON データを簡単にシリアル化および逆シリアル化できます。ただし、特別な注意が必要な重要なポイントがいくつかあります。

Go では json.Marshal() を使用して JSON データを簡単に取得できます。この関数に対応する 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 3f1c4e4b6b16bbbd69b2ee476dc4f83a tags, the string is encoded using HTMLEscape, which replaces "0c43feb88fe3846c3aee3dd8022b72eb", "&", 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 エンコードが実行され、「8a43c7dd0f94d2c178c3c05657689ef4」、「&」、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 文字列の後にこの関数 ソース コードは次のとおりです:

// 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
}

この関数はシリアル化後に別の

\n 文字を書き込むことがわかります。文字が必要ない場合は、追加の削除が必要です:

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

以上がGo json トラップ レコードを共有するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はlearnku.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。