バイト スライス ([]byte) を JSON 形式に変換しようとすると、開発者は予期しない文字列表現に遭遇することがよくあります。この記事では、この動作の理由を詳しく調べ、バイト スライスを正確にマーシャリングするための解決策を提供します。
次のコード スニペットを考えてみましょう。
import ( "encoding/json" "fmt" "os" ) func main() { type ColorGroup struct { ByteSlice []byte SingleByte byte IntSlice []int } group := ColorGroup{ ByteSlice: []byte{0, 0, 0, 1, 2, 3}, SingleByte: 10, IntSlice: []int{0, 0, 0, 1, 2, 3}, } b, err := json.Marshal(group) if err != nil { fmt.Println("error:", err) } os.Stdout.Write(b) }
場合実行すると、このコードは次のように出力します:
{"ByteSlice":"AAAAAQID","SingleByte":10,"IntSlice":[0,0,0,1,2,3]}
興味深いことに、ByteSlice フィールド、バイト配列が含まれているはずですが、「AAAAQID」としてレンダリングされています。
説明は、json パッケージのドキュメントにあります:
Array とスライス値は JSON 配列としてエンコードされます。ただし、[]byte は Base64 でエンコードされた文字列としてエンコードされ、nil スライスはnull JSON オブジェクト。
この場合、バイト配列である ByteSlice フィールドは、JSON 配列としてではなく、base64 でエンコードされた文字列としてエンコードされます。
[]byte データを期待どおりに JSON にマーシャリングするには、base64 表現をデコードする必要があります。コードの更新バージョンは次のとおりです:
package main import ( "encoding/base64" "encoding/json" "fmt" "os" ) func main() { type ColorGroup struct { ByteSlice []byte SingleByte byte IntSlice []int } group := ColorGroup{ ByteSlice: []byte{0, 0, 0, 1, 2, 3}, SingleByte: 10, IntSlice: []int{0, 0, 0, 1, 2, 3}, } // Decode ByteSlice from base64 before marshaling decodedByteSlice, err := base64.StdEncoding.DecodeString(string(group.ByteSlice)) if err != nil { fmt.Println("error:", err) } group.ByteSlice = decodedByteSlice b, err := json.Marshal(group) if err != nil { fmt.Println("error:", err) } os.Stdout.Write(b) }
結果の JSON 出力は、ByteSlice フィールドをバイト配列として正しく表現します:
{"ByteSlice":[0,0,0,1,2,3],"SingleByte":10,"IntSlice":[0,0,0,1,2,3]}
以上がGo の「json.Marshal」が []byte を Base64 文字列に変換するのはなぜですか?それを修正するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。