バイナリデータを JSON 用にエンコードする方法
画像やファイルのバイト列などのバイナリデータを、Base64 を使って JSON ドキュメントに安全に埋め込みます。
问题
JSON はテキストと数値しかサポートしませんが、JSON ペイロード内にバイナリデータ(例:小さな画像)を含める必要があります。
前提条件
- JSON 構造の理解
- Base64 の基礎知識
ステップ
-
1. Read the binary data as bytes
Load the file or binary blob into memory as a byte array. Do not attempt to interpret it as text, as null bytes and non-UTF-8 sequences will corrupt the data.
入力image.png (2048 bytes)输出Uint8Array[2048] -
2. Base64-encode the bytes
Convert the byte array to a Base64 string. This produces an ASCII-safe representation that JSON can carry as a regular string field. The encoded size will be about 4/3 of the original.
入力2048 bytes输出~2732 chars Base64 -
3. Embed in JSON and decode on receipt
Place the Base64 string as a JSON value. On the receiving end, Base64-decode it back to bytes and reconstruct the file. Add a field for the MIME type so the receiver knows how to handle it.
入力{"data":"iVBOR...","type":"image/png"}输出reconstructed PNG file
期待される結果
Base64 エンコードされたバイナリデータを含み、元のバイト列に正確に復元できる JSON 文字列。
よくあるエラー
- JSON parse error due to invalid characters
- Ensure the binary data was Base64-encoded and not inserted as raw bytes. Raw binary is not valid JSON.
- Corrupted file after decoding
- Verify the Base64 string was not truncated by a length limit in transit. Check that the decoded byte count matches the original.
トラブルシューティング指引
- If the payload is too large, consider sending the file via multipart upload instead of embedding in JSON.
- Always include the content type alongside the data so the receiver can interpret it correctly.
セキュリティ上の制限
- Base64 in JSON increases payload size by ~33%. Large binaries should be referenced by URL rather than embedded.