64

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?

JJJ
  • 32,902
  • 20
  • 89
  • 102
johni
  • 5,342
  • 6
  • 42
  • 70

4 Answers4

153

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

user1063287
  • 10,265
  • 25
  • 122
  • 218
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
81

You misunderstood the Buffer(str, [encoding]) constructor, the encoding tells the constructor what encoding was used to create str, or what encoding the constructor should use to decode str into a byte array.

Basically the Buffer class represents byte streams, it's only when you convert it from/to strings that encoding comes into context.

You should instead use buffer.toString("base64") to get base-64 encoded of the buffer content.

let objJsonStr = JSON.stringify(obj);
let objJsonB64 = Buffer.from(objJsonStr).toString("base64");
xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30
  • Thanks for the explanation. Regarding your example - it does not work on large JSONs. I've just checked that, the decode returns only partial of the original JSON. – johni Jun 30 '16 at 22:42
  • How big is your JSON? I tried some large ones and it's working fine. – xiaofeng.li Jun 30 '16 at 22:54
  • Yep, you're right. I probably selected only part of the encoded string. – johni Jun 30 '16 at 22:55
  • 3
    `new Buffer()` is now deprecated, you should use `Buffer.from()` instead, see [the doc](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding) – Cinn Oct 13 '17 at 14:14
9

You can easily encode and decode from and to JSON/Base64 using a Buffer:

JSON to Base64:

function jsonToBase64(object) {
  const json = JSON.stringify(object);
  return Buffer.from(json).toString("base64");
}

Base64 to JSON:

function base64ToJson(base64String) {
  const json = Buffer.from(base64String, "base64").toString();
  return JSON.parse(json);
}

atob() and btoa() are outdated and should no longer be used.

GD21
  • 223
  • 2
  • 10
2

When converting object to base64 I was getting out of latin range issues and character invalid error.

I made it work in my project with the below line.

Include the base64 and utf8 node packages and access them like this:

var bytes = base64.encode(utf8.encode(JSON.stringify(getOverviewComments())));
Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
Raphael
  • 1,738
  • 2
  • 27
  • 47