Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Convert JSON to ArrayBuffer in JavaScript?
In JavaScript, an ArrayBuffer is a kind of binary structure that enables the manipulation of raw binary data. While JSON represents data as strings, it is sometimes useful to convert JSON into an ArrayBuffer when working with binary APIs or when you need to optimize data transmission. In this article, we will explore two common methods for converting JSON objects into ArrayBuffers in JavaScript.
Approaches to Convert JSON to ArrayBuffer
- Using TextEncoder: Suitable for UTF-8 encoding (recommended).
- Manual Conversion with DataView: Useful for handling specific binary encoding formats or custom control.
Using TextEncoder (Recommended)
The TextEncoder API is the modern and preferred approach to create a UTF-8 encoded ArrayBuffer from a JSON string. It handles character encoding properly and is supported in all modern browsers and Node.js.
Example Code
// JSON data
const jsonData = { name: "Pankaj", age: 20, city: "Surat" };
// Convert JSON to string
const jsonString = JSON.stringify(jsonData);
console.log("JSON String:", jsonString);
// Encode string to ArrayBuffer using TextEncoder
const encoder = new TextEncoder();
const arrayBuffer = encoder.encode(jsonString).buffer;
console.log("ArrayBuffer:", arrayBuffer);
console.log("Byte Length:", arrayBuffer.byteLength);
// Convert back to verify
const decoder = new TextDecoder();
const decodedString = decoder.decode(arrayBuffer);
console.log("Decoded JSON:", JSON.parse(decodedString));
Output
JSON String: {"name":"Pankaj","age":20,"city":"Surat"}
ArrayBuffer: ArrayBuffer {
[Uint8Contents]: <7b 22 6e 61 6d 65 22 3a 22 50 61 6e 6b 61 6a 22 2c 22 61 67 65 22 3a 32 30 2c 22 63 69 74 79 22 3a 22 53 75 72 61 74 22 7d>,
byteLength: 41
}
Byte Length: 41
Decoded JSON: { name: 'Pankaj', age: 20, city: 'Surat' }
Manual Conversion with DataView
DataView provides low-level control for writing data directly into an ArrayBuffer. This approach is useful when you need custom binary encoding or want to understand the byte-level operations.
Example Code
// JSON data
const jsonData = { name: "Pankaj", age: 20, city: "Surat" };
// Convert JSON to string
const jsonString = JSON.stringify(jsonData);
console.log("JSON String:", jsonString);
// Create ArrayBuffer with byte length equal to string length
const arrayBuffer = new ArrayBuffer(jsonString.length);
const view = new DataView(arrayBuffer);
// Write each character code into the ArrayBuffer
for (let i = 0; i < jsonString.length; i++) {
view.setUint8(i, jsonString.charCodeAt(i));
}
console.log("ArrayBuffer:", arrayBuffer);
console.log("Byte Length:", arrayBuffer.byteLength);
// Read back to verify
let reconstructedString = "";
for (let i = 0; i < arrayBuffer.byteLength; i++) {
reconstructedString += String.fromCharCode(view.getUint8(i));
}
console.log("Reconstructed JSON:", JSON.parse(reconstructedString));
Output
JSON String: {"name":"Pankaj","age":20,"city":"Surat"}
ArrayBuffer: ArrayBuffer {
[Uint8Contents]: <7b 22 6e 61 6d 65 22 3a 22 50 61 6e 6b 61 6a 22 2c 22 61 67 65 22 3a 32 30 2c 22 63 69 74 79 22 3a 22 53 75 72 61 74 22 7d>,
byteLength: 41
}
Byte Length: 41
Reconstructed JSON: { name: 'Pankaj', age: 20, city: 'Surat' }
Comparison
| Method | Ease of Use | UTF-8 Support | Performance | Use Case |
|---|---|---|---|---|
| TextEncoder | High | Native | Fast | General purpose, recommended |
| DataView | Medium | Manual handling | Slower | Custom binary formats, learning |
Common Use Cases
Converting JSON to ArrayBuffer is useful for:
- Sending binary data over WebSockets or HTTP
- Working with File API and Blob objects
- Interfacing with WebAssembly modules
- Storing data in IndexedDB as binary
Conclusion
Use TextEncoder for most JSON-to-ArrayBuffer conversions as it handles UTF-8 encoding properly. DataView offers more control but requires manual character encoding handling.
