Open In App

How to Convert JSON to ArrayBuffer in JavaScript?

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Article Tags :

Similar Reads