Base64 编码一个 javascript 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38134200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Base64 encode a javascript object
提问by johni
I have large Javascript objects which I would like to encode to base-64 for AWS Kinesis` It turns out that:
我有大型 Javascript 对象,我想为 AWS Kinesis` 将其编码为 base-64 事实证明:
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?
如何对 JSON 进行 base-64 编码并安全地将其解码回其原始值?
回答by Zohaib Ijaz
From String to Base-64
从字符串到 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
https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
回答by xiaofeng.li
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.
你误解了Buffer(str, [encoding])
构造函数,它encoding
告诉构造函数使用什么编码来创建str
,或者构造函数应该使用什么编码来解码str
成字节数组。
Basically the Buffer
class represents byte streams, it's only when you convert it from/to strings that encoding comes into context.
基本上Buffer
该类表示字节流,只有当您将其从/转换为字符串时,编码才会进入上下文。
You should instead use buffer.toString("base64")
to get base-64 encoded of the buffer content.
您应该改为使用buffer.toString("base64")
来获取缓冲区内容的 base-64 编码。
let objJsonStr = JSON.stringify(obj);
let objJsonB64 = Buffer.from(objJsonStr).toString("base64");
回答by Raphael
When converting object to base64 I was getting out of latin range issuesand character invalid error.
将对象转换为 base64 时,我遇到了拉丁范围问题和字符无效错误。
I made it work in my project with the below line.
我用下面的行让它在我的项目中工作。
include these node packages base-64 and utf8 and access in the below manner.
包括这些节点包 base-64 和 utf8 并以以下方式访问。
var bytes = base64.encode(utf8.encode(JSON.stringify(getOverviewComments())));
var bytes = base64.encode(utf8.encode(JSON.stringify(getOverviewComments())));