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.
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