The Wayback Machine - https://web.archive.org/web/20240915134945/https://www.geeksforgeeks.org/how-to-convert-json-to-arraybuffer-in-javascript/
Open In App

How to Convert JSON to ArrayBuffer in JavaScript?

Last Updated : 03 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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); 

Output
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 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); 

Output
ArrayBuffer {
  [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.



Previous Article
Next Article

Similar Reads

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 JavaScript is a generic, fixed-length binary data buffer,
2 min read
Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json?
In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config
6 min read
Convert JSON String to Array of JSON Objects in JavaScript
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solving this problem, which are discussed below: Table of Content Using JSON.parse() MethodUsing JavaScript eval() MethodUsing Function ConstructorU
4 min read
JavaScript arrayBuffer byteLength Property
The Javascript arrayBuffer.byteLength is a property in JavaScript that return the length of an ArrayBuffer in a byte. ArrayBuffer is an object which is used to represent fixed-length binary data. Difference between property and function in javascript. Property in JavaScript is nothing but a value whereas method is a function this can be understood
4 min read
JavaScript arrayBuffer slice() Method
The arrayBuffer.slice is a property in JavaScript that return another arrayBuffer containing the contents of the previous arrayBuffer from beginning inclusive, to end, exclusive in bytes. ArrayBuffer is an object which is used to represent fixed-length binary data. Difference between property and function in javascript. Property in JavaScript is no
2 min read
JavaScript arrayBuffer.byteLength Property
The Javascript arrayBuffer.byteLength is a property in JavaScript that gives the length of an arrayBuffer in bytes. Syntax: ArrayBuffer.byteLengthParameters: It does not accept any parameter because arrayBuffer.byteLength is a property, not a function. Return Value: It returns the length of an arrayBuffer in bytes. JavaScript code to show the worki
2 min read
JavaScript ArrayBuffer isView() Method
The Javascript ArrayBuffer.isView() is an inbuilt function in JavaScript that is used to check whether the given argument for the function is a typed array or not. Syntax: ArrayBuffer.isView(p) Parameters: It accepts a parameter either in the form of a typed array or something else. Return Values: It returns true if the parameter is typed array oth
2 min read
JavaScript ArrayBuffer() Constructor
JavaScript ArrayBuffer Constructor is used to create a new ArrayBuffer object. ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. This object can only be created with the new keyword. If the object is created without the new keyword it will throw a TypeError Syntax: new ArrayBuffer(byteLength, opt) Parameters: I
2 min read
JavaScript ArrayBuffer Reference
ArrayBuffer is used to represent a generic, fixed-length raw binary data buffer. The contents of an ArrayBuffer cannot be directly manipulated and can only be accessed through a DataView Object or one of the typed array objects. These Objects are used to read and write the contents of the buffer. Syntax: new ArrayBuffer(byteLen) Parameters: It take
2 min read
JavaScript ArrayBuffer resizable Property
JavaScript resizable property in ArrayBuffer is used to check whether an ArrayBuffer can be resized or not. It returns a boolean value. It is a read-only property whose value is set when maxByteLength is defined. Syntax: arr.resizable Parameters: It does not accept any parameter. Example 1: In this example, we will check if the ArrayBuffers are res
1 min read
JavaScript ArrayBuffer maxByteLength Property
JavaScript maxByteLength in ArrayBuffer is used to set the maximum size of ArrayBuffer in bytes. This specified length is the maximum length to which we can resize the ArrayBuffer. This is a read-only property and can only be set when the ArrayBuffer object is created and cannot be changed afterward. If this property is left blank it is by default
2 min read
JavaScript ArrayBuffer constructor Property
JavaScript ArrayBuffer constructor property is used to return the ArrayBuffer constructor function for the object. The function returned by this property is just the reference, not the actual ArrayBuffer. It is an object property of JavaScript and can be used with Strings, Numbers, etc. Syntax: arraybuffer.constructor Return Value: ArrayBuffer() {
1 min read
JavaScript ArrayBuffer resize() Method
JavaScript resize() method in ArrayBuffer is used to increase or decrease the size of ArrayBuffer in JavaScript. This method specifies the change in length in bytes and the specified length cannot be greater than the maxByteLength property of the array Buffer. Syntax: resize(len) Parameter: This method takes only a single parameter. len: This is th
1 min read
JavaScript ArrayBuffer.prototype.detached
In JavaScript, the ArrayBuffer.prototype.detached property indicates whether an ArrayBuffer instance has been transferred (detached) from its current context. This is especially important for web workers when dealing with large binary data for communication. Syntaxconst isDetached = arrayBufferInstance.detached;const buffer = new ArrayBuffer(16); /
2 min read
JavaScript ArrayBuffer.prototype.transfer() Method
The transfer() method of ArrayBuffer create a new ArrayBuffer that has the same byte content as the current buffer, then detach this current buffer, this means that merely the fresh buffer is able to get at the buried data and not any else. Such an option as transfer() comes in handy when there is a need to shift ArrayBuffers ownership between dive
2 min read
Node.js NPM arraybuffer-to-string Module
NPM(Node Package Manager) is a package manager of Node.js packages. There is an NPM package called arraybuffer-to-string used to decode array buffers in actual strings. The package not only converts the buffer to 'utf8' string but also it converts the buffer to many forms like base64 encoded string, a hex-encoded string that we use in many contexts
4 min read
Node.js NPM string-to-arraybuffer Module
NPM(Node Package Manager) is a package manager of Node.js packages. There is a NPM package called 'shortid' used to short non-sequential url-friendly unique ids. Command to install: npm install string-to-arraybuffer Syntax to import the package in local file const str2ab = require('string-to-arraybuffer') Syntax to convert string to an array buffer
5 min read
What is the Difference Between an Array and an ArrayBuffer?
The arrays and ArrayBuffers serve different purposes and are used in the different contexts. While arrays are used for the general data storage and manipulation. The ArrayBuffers are used for the handling binary data. Understanding the differences between these two data structures is essential for the efficiently managing data in various scenarios.
2 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to Convert JavaScript Class to JSON in JavaScript?
When transmitting or saving class data in a structured manner, converting an instance of a class into a JSON format is also necessary. JSON (JavaScript Object Notation) supplies a method of turning objects into strings. They can be sent across a network or stored in a database, properties of the instance of the class should be taken out and changed
2 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
Difference between package.json and package-lock.json files
In Node, package.json file contains the list of dependencies and scripts in a project while the package.lock.json specifies their respective versions to ensure consistent installations in different environments. In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. Table of Content
4 min read
JavaScript | Convert an array to JSON
Here is a need to convert an array into a JSON_Object. To do so we are going to use a few of the most preferred techniques. First, we need to know a few methods. 1) Object.assign() method This method copies the values of all properties owned by enumerables from source objects(one or more) to a target object. Syntax: Object.assign(target, ...sources
2 min read
How to convert JSON results into a date using JavaScript ?
The task is to convert a JSON result to JavaScript Date with the help of JavaScript. There are two methods which are discussed below: Approach 1: Use substr() method to get the integer part of the string.Use the parseInt() method followed by Date() to get the JavaScript date. Example: This example implements the above approach. C/C++ Code &lt;h1 st
2 min read
How to Convert CSV to JSON file and vice-versa in JavaScript ?
CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality. In this article, we will explain how to c
3 min read
How to Convert Excel to JSON in JavaScript ?
Converting Excel spreadsheets to JSON format is a common requirement in various applications. JavaScript code utilizes the read-excel-file library to parse the Excel data, convert it to JSON format, and display it. Additionally, it provides functionality to download the generated JSON file. ApproachCreate an HTML file with a div containing an input
3 min read
Article Tags :