Convert a base64 Encoded String to Real Object in React
A base64 encoded string is just a representation of binary data as ASCII text. We cannot directly convert a base64 encoded string to a real object.
However, we can decode the base64 encoded string to get the binary data, and then use appropriate techniques to convert that data to a real object.
Let's see in action with an example:
//a base64 encoded string
const base64String = "eyJpZCI6MSwiYWdlIjozMCwibGFzdE5hbWUiOiJKb2huIiwicGhvbmVOdW1iZXIiOiIwNzE1MjM0NTY3OCJ9";
Here's a base64 encoded string.
In the above code, we now decode the base64 string using the atob function.
// Decode the base64 encoded string
const decodedString = atob(base64String);
Now we will use JSON.parse to parse the decoded string to real object-
// Convert the binary data to a real object
const object = JSON.parse(decodedString);
console.log(object);
in console:
Another way can be like first create a new Uint8Array and iterate over the decoded string, setting each byte of the array to the corresponding character code of the decoded string. And then, we convert the byte array into a string using String.fromCharCode.apply, and then parse the resulting string into a JavaScript object using JSON.parse.
// convert the binary data to Unit8Array
const byteArray = new Uint8Array(decodedString.length);
// set each byte of the array to the corresponding character code
for (let i = 0; i < decodedString.length; i ) {
byteArray[i] = decodedString.charCodeAt(i);
}
// convert the byte array into a string
const string = String.fromCharCode.apply(null, byteArray);
const obj = JSON.parse(string);
console.log(obj);
The output result will be the same.
Note: If the object is in a different format like (xml, yaml, bson etc) , you will need to use a different method to parse it.
Tayeb Khan
Software Engineer