base64 encoded data to object in javascript

Converting Base64 Encoded Data to Object in JavaScript

Base64 encoding is a process of converting binary data into a string of ASCII characters. This is often used for transmission of data over the internet, where some protocols may not support binary data transfer. In JavaScript, we can convert a Base64 encoded data to an object by decoding it back to binary and then parsing it as JSON or other object formats.

Using atob() Function

The easiest way to decode Base64 data in JavaScript is by using the atob() function. This function decodes a Base64 string to binary data.

let base64Data = "eyJtb2R1bGUiOiJIZWxsbyIsInByb2R1Y3RzIjpbXSwidGV4dCI6IkhlbGxvIHdvcmxkIn0=";
let binaryData = atob(base64Data);
let object = JSON.parse(binaryData);

In the above code, we first define a variable base64Data containing our encoded data. We then use the atob() function to decode this data into binary data. Finally, we parse this binary data as a JSON object using the JSON.parse() function.

Using Buffer.from() Function

In Node.js and modern browsers, we can also use the Buffer.from() function to convert Base64 data to binary data. This function returns a buffer object which can be parsed into an object.

let base64Data = "eyJtb2R1bGUiOiJIZWxsbyIsInByb2R1Y3RzIjpbXSwidGV4dCI6IkhlbGxvIHdvcmxkIn0=";
let binaryData = Buffer.from(base64Data, 'base64');
let object = JSON.parse(binaryData);

In the above code, we first define a variable base64Data containing our encoded data. We then use the Buffer.from() function with the 'base64' encoding option to convert this data into binary data. Finally, we parse this binary data as a JSON object using the JSON.parse() function.

Conclusion

Converting Base64 encoded data to an object in JavaScript is a simple process. We can use the atob() function or Buffer.from() function to convert the encoded data into binary data and then parse it as JSON or other object formats.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe