Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Convert JSON to ArrayBuffer in JavaScript



In JavaScript, an ArrayBuffer is a kind of binary structure that enables the manipulation of unprocessed binary. While there is a representation of data with the use of strings such as JSON, it is sometimes useful to indicate that JSON could be transformed into an ArrayBuffer especially when interacting with binary APIs or when there is a need to compress data areas. In this article, we will focus on three widespread methods of converting a JSON object into an ArrayBuffer in JavaScript.

Approaches to Convert JSON to ArrayBuffer

Using TextEncoder

TextEncoder API allows you to create a UTF-8 encoded ArrayBuffer from a JSON string by converting it. This is a straightforward and useful method for those who require the UTF-8 encoding.

Exmple Code

// JSON data
const jsonData = { name: "Pankaj", age: 20, city: "Surat" };

// Convert JSON to string
const jsonString = JSON.stringify(jsonData);

// Encode string to ArrayBuffer
const encoder = new TextEncoder();
const arrayBuffer = encoder.encode(jsonString).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 2c 22 63 69 74 79 22 3a 22 53 75 72 61 74 22 7d>,
  byteLength: 41
}

Manual Conversion with DataView

If you need more control over the encoding process or want to handle data at the byte level, DataView can be used to manually write JSON data to an ArrayBuffer.

Exmple Code

// JSON data
const jsonData = { name: "Pankaj", age: 20, city: "Surat" };

// Convert JSON to string
const jsonString = JSON.stringify(jsonData);

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

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 2c 22 63 69 74 79 22 3a 22 53 75 72 61 74 22 7d>,
  byteLength: 41
}
Updated on: 2024-11-14T13:31:50+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements