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

How To Convert Base64 to JSON String in JavaScript?

Last Updated : 13 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There could be situations in web applications, where there is a need to decode the data from Base64 format back into its original JSON format. It generally happens when one has to transmit data over the network where Base64 encoding is well suited for encoding binary data.

In this article, we will see how one can convert Base64 strings into JSON-formatted strings in JavaScript.

Different approaches to convert Base64 to JSON String in JavaScript.

Approach 1: Using atob() and JSON.parse()

There are occasions, especially within web browsers when Base64 data and JSON have to be decoded and parsed separately.

  • In the first step, we will use atob() function which converts Base64 string into a plain text string.
  • In the last step, we will use JSON.parse() for conversion of the decoded string into a a JSON object.
HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Convert Base64 to JSON String</title>
</head>

<body>
    <h1>GeeksForGeeks</h1>
    <h3>Base64 to JSON Conversion</h3>
    <button id="convert-btn">Convert Base64 to JSON</button>
    <pre id="result"></pre>

    <script>
        // Sample Base64-encoded JSON string
        const base64Data = 
             "eyAiTmFtZSI6ICJQYW5rYWogQmluZCIsICJBZ2UiOiAyMSwgIkNvdW50cnkiOiAiSW5kaWEiIH0=";

        // Function to convert Base64 to JSON
        function convertBase64ToJson() {
            try {
                // Decode Base64 to string
                const jsonString = atob(base64Data);

                // Parse string to JSON
                const jsonObject = JSON.parse(jsonString);

                // Display the JSON object
                document.getElementById("result").textContent = 
                    JSON.stringify(jsonObject, null, 2);
            } catch (error) {
                console.error("Error decoding Base64:", error);
            }
        }

        // Event listener for the convert button
        document.getElementById("convert-btn").addEventListener("click", convertBase64ToJson);
    </script>
</body>

</html>


Output

1
atob() and JSON.parse()

Approach 2: Using Buffer in Node.js

This approach is adequate for JavaScript running on a server (Node.js) and where one has to deal with Binary and Base64 encoding.

  • In first step you have to create a Buffer from Base64 string using Buffer.from(base64Data, ‘base64’).
  • Use buffer.toString(‘utf-8’) and change the Buffer to a UTF-8 string.
  • In last step we will use JSON.parse() for converting string into JSON object.
JavaScript
// Node.js Example

// Sample Base64-encoded JSON string
const base64Data = 
"eyAiTmFtZSI6ICJQYW5rYWogQmluZCIsICJBZ2UiOiAyMSwgIkNvdW50cnkiOiAiSW5kaWEiIH0=";

// Convert Base64 to buffer
const buffer = Buffer.from(base64Data, 'base64');

// Convert buffer to string and parse to JSON
const jsonString = buffer.toString('utf-8');
const jsonObject = JSON.parse(jsonString);

console.log(jsonObject);

Output
{ Name: 'Pankaj Bind', Age: 21, Country: 'India' }

Similar Reads

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 functionUsing Manual ConversionUsing btoa functionIn this approach, we're using btoa to encode a UTF-8 string representation of a JSON object. First, the JSON data is converted to
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 base64 String to ArrayBuffer In JavaScript
A Base64 string represents binary data in an ASCII string format by translating it into a radix-64 representation. Often used to encode binary data in text-based formats like JSON or HTML, it needs to be converted back into its original binary format for further processing. An ArrayBuffer in JavaScript is a generic, fixed-length binary data buffer,
2 min read
Convert JSON String to Array of JSON Objects in JavaScript
Converting a JSON string to an array of JSON objects in JavaScript involves transforming a structured text format (JSON) into a usable JavaScript array. This allows developers to work directly with the data, enabling easier manipulation, analysis, and display of information. There are two approaches to solving this problem, which are discussed belo
2 min read
How to convert blob to base64 encoding using JavaScript ?
Blob in JavaScript is a fundamental data type representing bytes of data. It serves as the underlying structure for files and is supported by web browsers, capable of storing and retrieving data from memory. Blobs have specific sizes and file types like regular files and can be handled with Buffers, ideal for binary data storage such as images or f
2 min read
How to Convert Base64 to File in JavaScript?
In web development, Base64 encoding is often used to represent binary data, such as images or files, with a string of ASCII characters, sometimes you may be required to change this Base64 string back into a file for instance for file uploads, downloads, or processing in the browser, this article aims to discuss different ways of converting Base64 s
2 min read
How to Convert Base64 to Blob in JavaScript?
Working with files and data in web applications often involves dealing with binary data. One common scenario is converting a Base64 string into a Blob object, which can then be used in various ways, such as creating downloadable files or uploading images to a server. This article will guide you through converting a Base64 string to a Blob in JavaSc
4 min read
Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json?
In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config
6 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 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
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
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
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
How to display Base64 images in HTML ?
Base64 is a widely used method for encoding binary data, such as images, into ASCII text. This enables embedding binary data, such as images, directly into HTML without needing separate image files. In the context of web development, Base64 encoding is often used to improve page performance, security, and compatibility by reducing the number of ext
4 min read
How Base64 Encoding and Decoding is Done in Node.js ?
Base64 encoding and decoding are when you need to encode binary data into a text format that can be easily transmitted over text-based protocols like HTTP. Node.js provides built-in methods for Base64 encoding and decoding, which can be easily performed using the Buffer class. Table of Content ApproachEncoding the original string to base64Decoding
3 min read
How to Convert String to JSON in JavaScript?
In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Using eval()Using Function ConstructorUsing JSON.par
2 min read
How to Convert JSON to string in JavaScript ?
In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission. Several methods can be used to Convert JSON to string in JavaScript, which ar
3 min read
How to Convert a Map to JSON String in JavaScript ?
A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript. However, JSON.stringify() does not directly support Map objects. Table of Content Using Object.fromEntries() MethodUsing Array Spread and ReduceHandling Nested MapsUsing A
2 min read
How to Convert JS Object to JSON String in JQuery/Javascript?
Converting a JavaScript object to a JSON string means using the JSON.stringify() method to transform the object into a JSON-formatted string. This allows for efficient data storage, transmission, and debugging by representing complex data structures in a standardized text format. To Convert JS Object to JSON String in JQuery/Javascript we can use t
4 min read
How to Convert JavaScript Class to JSON in JavaScript?
When transmitting or saving class data in a structured manner, converting an instance of a class into a JSON format is also necessary. JSON (JavaScript Object Notation) supplies a method of turning objects into strings. They can be sent across a network or stored in a database, properties of the instance of the class should be taken out and changed
2 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
Difference between package.json and package-lock.json files
In Node, package.json file contains the list of dependencies and scripts in a project while the package.lock.json specifies their respective versions to ensure consistent installations in different environments. In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. Table of Content
4 min read
Check if a String is Valid JSON String using JavaScript
In JavaScript, JSON (JavaScript Object Notation) is a format used for representing structured data as text. It's widely used for data exchange between web servers and browsers. Sometimes, we need to check if a given string is a valid JSON before using it in our code. If the string follows the correct JSON format, we return true, otherwise, we retur
5 min read
How to Convert a JSON String into an SQL Query?
JSON to SQL conversion is complicated because both have different structure. but this the help of the article you can easily convert JSON into SQL. We will use JavaScript language for conversion. Approach: Using JavaScript Validate JSON Format.Parse the JSON String into a JSON ObjectExtract Values from the JSON Object.Concat extract values and deve
2 min read
How to Convert an Object to a JSON String in Typescript ?
In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do. Table of Content Using JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsing TypeScript Decorators for SerializationUsing a
5 min read
How to convert tabular string to JSON using Node.js ?
Tabular: Information that is displayed in a table with rows and columns is known as "tabular format". A data table is an organized and practical approach to displaying a significant amount of information that contains repeated data items. The majority of office productivity software packages, including word processing software and spreadsheets, hav
5 min read
Article Tags :
three90RightbarBannerImg