How to use btoa function In Javascript

In this approach, we’re using btoa to encode a UTF-8 string representation of a JSON object. First, the JSON data is converted to a UTF-8 string using unescape and encodeURIComponent, and then btoa encodes this UTF-8 string to Base64.

Syntax:

const base64String = btoa(stringToEncode);

Example: The below example uses btoa function to convert JSON to Base64 in JavaScript.

JavaScript
const jData = {
    name: 'GFG',
    age: 30
};
const utf8Str = unescape(encodeURIComponent
    (JSON.stringify(jData)));
const res = btoa(utf8Str);
console.log(res);

Output
eyJuYW1lIjoiR0ZHIiwiYWdlIjozMH0=

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 function
  • Using Manual Conversion

Similar Reads

Using btoa function

In this approach, we’re using btoa to encode a UTF-8 string representation of a JSON object. First, the JSON data is converted to a UTF-8 string using unescape and encodeURIComponent, and then btoa encodes this UTF-8 string to Base64....

Using Manual Conversion

In this approach, we’re manually converting a JSON string to Base64. The function conversionFn encodes the UTF-16 characters of the JSON string into Base64 using a custom algorithm that follows the Base64 encoding table, including handling padding characters (‘=’)....