How to Convert JSON to ArrayBuffer in JavaScript?
Last Updated :
03 Sep, 2024
An ArrayBuffer is a complex data type, and structures which has a fixed length and takes binary content as the whole. Any variable that contains pure binary data will be defined in JavaScript as Simple Data, however on some occasions it is sometimes necessary to convert JSON data to an ArrayBuffer, for example when the objective is to manipulate images or other forms of non-text data that involve using web application program interfaces that accept binary input.
Below are the following approaches to convert JSON to ArrayBuffer in JavaScript:
Using TextEncoder (UTF-8 Encoding)
This method utilizes TextEncoder API that encodes text into binary data(0s and 1s) in the form of Uint8Array, this array type is then used to form an ArrayBuffer, the TextEncoder encodes a string of JSON characters that is in UTF-8 format into bytes which are saved in the ArrayBuffer, to perform this, a JSON object is first and foremost constructed and the stringify() function is used.
- Firstly you have to convert JSON object to a string using JSON.stringify().
- Make use of TextEncoder.
- Get the ArrayBuffer that was held by the Uint8Array.
Example: The ArrayBuffer
represents a fixed-length binary data buffer. In this case, it holds the UTF-8 encoded bytes of the JSON string. It does not have a specific format or interpretation of the data, only the raw byte sequence.
JavaScript
const json = { name: "Pankaj", age: 20 };
// Step 1: Convert JSON to a string
const jsonString = JSON.stringify(json);
// Step 2: Encode the string to UTF-8
const encoder = new TextEncoder();
const uint8Array = encoder.encode(jsonString);
// Step 3: Extract the ArrayBuffer
const arrayBuffer = uint8Array.buffer;
console.log(arrayBuffer);
OutputArrayBuffer {
[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 7d>,
byteLength: 26
}
Manual Conversion to Binary (UTF-16 Encoding)
Each of the characters in the JSON string is manually encoded using binary (specifically UTF-16 encoding) and this is retained in an ArrayBuffer, with this approach we go through JSON string’s characters and their UTF-16 codes in every object and store them in an ArrayBuffer.
- Firstly you have to convert JSON object to a string using JSON.stringify().
- An ArrayBuffer is created that would be capable of containing the binary data.
- A DataView is employed to store each character’s UTF-16 code to buffer.
Example: The ArrayBuffer
contains the binary representation of the JSON string encoded in UTF-16, where each character is stored as 2 bytes (16 bits) in little-endian order. This buffer allows for manipulation of the underlying binary data directly.
JavaScript
const json = { name: "Pankaj", age: 20 };
// Step 1: Convert JSON to a string
const jsonString = JSON.stringify(json);
// Step 2: Allocate an ArrayBuffer
const buffer = new ArrayBuffer(jsonString.length * 2);
// UTF-16 takes 2 bytes per character
const view = new DataView(buffer);
// Step 3: Write each character's code into the ArrayBuffer
for (let i = 0; i < jsonString.length; i++) {
view.setUint16(i * 2, jsonString.charCodeAt(i), true);
}
console.log(buffer);
OutputArrayBuffer {
[Uint8Contents]: <7b 00 22 00 6e 00 61 00 6d 00 65 00 22 00 3a 00 22 00 50 00 61 00 6e 00 6b 00 61 00 6a 00 22 00 2c 00 22 00 61 00 67 00 65 00 22 00 3a 00 32 00 30 00 7d 00>,
byteLength: 52
}
Conclusion
Transforming JSON into an ArrayBuffer is one of the fundamental operations encountered when manipulating binary data in Javascript’s environment, TextEncoder is the easiest and the most up to date approach for this as it converts text content into UTF-8 in a simplified manner, but there are also a number of other ways of doing so such as manual wit dataview or use of blob with file reader etc, people choose a method dependent upon the encoding format and the target API/application characteristics requirements.
Similar Reads
How to Convert JSON to base64 in JavaScript ?
Base 64 is the encoding scheme that represents binary data in a printable ASCII format, commonly used for data serialization and transmission. Table of Content Using btoa functionUsing Manual ConversionUsing btoa functionIn this approach, we're using btoa to encode a UTF-8 string representation of a
2 min read
How to Convert JSON to Blob in JavaScript ?
This article explores how to convert a JavaScript Object Notation (JSON) object into a Blob object in JavaScript. Blobs represent raw data, similar to files, and can be useful for various tasks like downloading or processing JSON data. What is JSON and Blob?JSON (JavaScript Object Notation): A light
2 min read
How to Convert String of Objects to Array in JavaScript ?
This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
4 min read
How to Convert XML to JSON in JavaScript ?
To convert XML to JSON in JavaScript, various methods and libraries and be used. Here, we use xml-js library that provides xml2json function to convert XML to JSON data. It takes XML data as input and gives the JSON objects as output. We can also use the DOMParser from the xmldom package to convert
2 min read
How to Convert CSV to JSON in JavaScript ?
In this article, we will explain different ways to change Comma-Separated Values (CSV) data into JavaScript Object Notation (JSON) format, step-by-step. We'll break down each method with clear explanations and examples. There are several approaches available in JavaScript to convert CSV to JSON in J
3 min read
How to Convert Blob Data to JSON in JavaScript ?
When dealing with Blob data in JavaScript, such as binary data or files, we may need to convert it into JSON format for doing so JavaScript provides us with various methods as listed below. Table of Content Using FileReader APIUsing TextDecoder APIUsing FileReader APIIn this approach, we first use t
2 min read
Convert an Array to JSON in JavaScript
Given a JavaScript Array and the task is to convert an array to JSON Object. Below are the approaches to convert an array to JSON using JsvaScript: Table of Content JSON.stringify() methodObject.assign() methodJSON.stringify() methodThe use of JSON is to exchange data to/from a web server. While sen
2 min read
How to Convert HTML to JSON in JavaScript ?
Converting HTML to JSON is important for structured data extraction and integration with JavaScript applications. Here, we will learn different approaches to converting HTML to JSON in JavaScript. Below are the approaches to convert html to JSON in JavaScript: Table of Content Using html-to-json Lib
2 min read
Convert base64 String to ArrayBuffer In JavaScript
A Base64 string represents binary data in an ASCII string format by translating it into a radix-64 representation. Often used to encode binary data in text-based formats like JSON or HTML, it needs to be converted back into its original binary format for further processing. An ArrayBuffer in JavaScr
2 min read
How To Convert Base64 to JSON String in JavaScript?
There could be situations in web applications, where there is a need to decode the data from Base64 format back into its original JSON format. It generally happens when one has to transmit data over the network where Base64 encoding is well suited for encoding binary data. In this article, we will s
2 min read