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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read