Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 encode a javascript object

I have large Javascript objects which I would like to encode to base-64 for AWS Kinesis` It turns out that:

let objStr = new Buffer(JSON.stringify(obj), 'ascii'); new Buffer(objStr, 'base64').toString('ascii') !== objStr 

I'm trying to keep this as simple as possible.

How can I base-64 encode JSON and safely decode it back to its original value?

like image 378
johni Avatar asked Jun 30 '16 22:06

johni


People also ask

What is the purpose of base64 encoding?

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with ASCII. This is to ensure that the data remain intact without modification during transport.

What is base64 string?

In computer programming, Base64 is a group of binary-to-text encoding schemes that represent binary data (more specifically, a sequence of 8-bit bytes) in sequences of 24 bits that can be represented by four 6-bit Base64 digits.

What is BTOA Javascript?

btoa() The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).


1 Answers

From String to Base-64

var obj = {a: 'a', b: 'b'}; var encoded = btoa(JSON.stringify(obj)) 

To decode back to actual

var actual = JSON.parse(atob(encoded)) 

For reference look here.

https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

like image 89
Zohaib Ijaz Avatar answered Oct 04 '22 13:10

Zohaib Ijaz