How to Encode Binary Data for JSON
Safely embed binary data like images or file bytes into a JSON document using Base64.
Problem
JSON only supports text and numbers, but you need to include binary data (e.g., a small image) inside a JSON payload.
Prerequisites
- Understanding of JSON structure
- Basic Base64 knowledge
Steps
-
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.
Inputimage.png (2048 bytes)OutputUint8Array[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.
Input2048 bytesOutput~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.
Input{"data":"iVBOR...","type":"image/png"}Outputreconstructed PNG file
Expected result
A JSON string containing Base64-encoded binary data that round-trips to the exact original bytes.
Common errors
- 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.
Troubleshooting
- 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.
Security limits
- Base64 in JSON increases payload size by ~33%. Large binaries should be referenced by URL rather than embedded.
Related tools
Related glossary
Related tasks
Ready to run it?