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

How to Convert JSON to base64 in JavaScript ?

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Base 64 is the encoding scheme that represents binary data in a printable ASCII format, commonly used for data serialization and transmission.

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.

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=

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 (‘=’).

Example: The below example uses Manual Conversion to convert JSON to Base64 in JavaScript.

JavaScript
const jData = {
    name: 'GFG',
    age: 30
};
const jStr = JSON.stringify(jData);
const baseTable = 
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

function conversionFn(str) {
    let res = '';
    let i = 0;
    while (i < str.length) {
        const c1 = str.charCodeAt(i++);
        const c2 = str.charCodeAt(i++);
        const c3 = str.charCodeAt(i++);
        const triplet = (c1 << 16) | (c2 << 8) | c3;
        const b64c1 = baseTable.
            charAt((triplet >>> 18) & 0x3F);
        const b64c2 = baseTable.
            charAt((triplet >>> 12) & 0x3F);
        const b64c3 = baseTable.
            charAt((triplet >>> 6) & 0x3F);
        const b64c4 = baseTable.
            charAt(triplet & 0x3F);
        res += b64c1 + b64c2 + b64c3 + b64c4;
    }
    const padding = str.length % 3;
    if (padding === 1) {
        res = res.slice(0, -2) + '==';
    } else if (padding === 2) {
        res = res.slice(0, -1) + '=';
    }
    return res;
}
const res = conversionFn(jStr);
console.log(res);

Output
eyJuYW1lIjoiR0ZHIiwiYWdlIjozMH0=


Similar Reads

How to convert blob to base64 encoding using JavaScript ?
Blob is a fundamental data type in JavaScript. Blob stands for Binary Large Object and it is a representation of bytes of data. Web browsers support the Blob data type for holding data. Blob is the underlying data structure for the File object and the FileReader API. Blob has a specific size and file type just like ordinary files and it can be stor
2 min read
How to convert image into base64 string using JavaScript ?
In this article, we will convert an image into a base64 string using Javascript. The below approaches show the methods to convert an image into a base64 string using Javascript. ApproachHere we will create a gfg.js file which will include JavaScript code and one gfg.html file.Now we will put onchange on the input type and this will execute a functi
2 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 solve this problem, which are discussed below: Approach 1: Using JSON.parse() MethodThe basic method to convert JSON String to Array of JSON object
2 min read
How to convert an image to base64 encoding in PHP?
The base64_encode() function is an inbuilt function in PHP which is used to convert any data to base64 encoding. In order to convert an image into base64 encoding firstly need to get the contents of file. This can be done with the help of file_get_contents() function of PHP. Then pass this raw data to base64_encode() function to encode. Required Fu
2 min read
JavaScript | Encode/Decode a string to Base64
To encode or decode strings in JavaScript, we can use the built-in functions provided by the language. These functions help in encoding special characters in a URL or decoding encoded strings back to their original form. 1. btoa() MethodThis method encodes a string in base-64 and uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode t
6 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 Base64 encoding and decoding is done in node.js ?
Base64 encoding and decoding can be done in Node.js using the Buffer object. Encoding the original string to base64: The Buffer class in Node.js can be used to convert a string to a series of bytes. This can be done using the Buffer.from() method that accepts the string to be converted and the current encoding of the string. This encoding can be sp
2 min read
How to validate if input in input field has base64 encoded string using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. If In a certain input field only base 64 encoded string are allowed i.e there not allowed any other form of string which not const
4 min read
Is embedding background image data into CSS as Base64 good or bad practice ?
One approach is to use external image files that are loaded separately by the browser. Another option is to embed the image data directly into the HTML or CSS code using Base64 encoding. In this article, we will explore whether embedding background image data into CSS as Base64 is a good or bad practice. Base64 Encoding: Base64 is a technique used
4 min read
three90RightbarBannerImg