如何Encode Binary Data 为 JSON
安全 embed 二进制数据 like images 或 file bytes 为 JSON document using Base64.
问题
JSON 仅 supports 文本和 numbers, 但你 need 到包含二进制数据 (e.g., 小图像) 内部 JSON 载荷.
前置条件
- Understanding 的 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
预期结果
JSON 字符串 containing Base64-encoded 二进制数据该 round-trips 到 exact 原始 bytes.
常见错误
- 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.
相关工具
Base64 编码器
将文本或二进制数据编码为 Base64。免费、隐私优先、100% 纯客户端运行。支持 UTF-8、ASCII、Latin1、UTF-16LE 字符集,可处理多语言文本与二进制内容,结果可直接用于 Data URI、邮件附件、JWT 等场景。 工具
Base64 解码器
将 Base64 数据解码为可读文本。免费、隐私优先、100% 纯客户端运行。支持 UTF-8、ASCII、Latin1、UTF-16LE 字符集,可处理 Data URI、JWT 载荷、邮件附件等场景,遇到非法输入会明确报错而非静默产生乱码。 工具
JSON 格式化器
在线格式化、压缩或排序 JSON。免费、隐私本地化、100% 客户端运行。支持 2 空格缩进美化、单行压缩、递归按键排序,遇到语法错误会精确定位行号与列号,适合调试 API 响应、配置文件与数据交换格式。 工具