Categories
JavaScript Answers

How to base64 encode a JavaScript object?

Spread the love

To base64 encode a JavaScript object, we convert it to a JSON string and base64 encode that.

For instance, we write

const obj = { a: "a", b: "b" };
const encoded = btoa(JSON.stringify(obj));
const actual = JSON.parse(atob(encoded));

to call JSON.strignify to convert obj to a JSON string.

Then we call btoa to convert the JSON string into a base64 string.

And we convert the base64 string back to an object with atob and JSON.parse.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.