javascript JSON.stringify 或如何将二进制数据序列化为 base64 编码的 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27232604/
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
JSON.stringify or how to serialize binary data as base64 encoded JSON?
提问by Sebastian Barth
I have a Javascript object which will consists of a non-cyclic object hierarchy with parameters and child objects. Some of these objects may hold binary data loaded from files or received via XHRs (not defined yet if Blob, ArrayBuffer or something else).
我有一个 Javascript 对象,它将由一个带有参数和子对象的非循环对象层次结构组成。其中一些对象可能保存从文件加载或通过 XHR 接收的二进制数据(如果 Blob、ArrayBuffer 或其他东西尚未定义)。
Normally I would use JSON.stringify() to serialize it as JSON but how can I then specify that binary data will be base64 encoded?
通常我会使用 JSON.stringify() 将它序列化为 JSON 但我如何指定二进制数据将被 base64 编码?
What binary data object (Blob, ArrayBuffer,...) would you recommend me then?
那么你会推荐我什么二进制数据对象(Blob,ArrayBuffer,...)?
EDIT: Other data formats than plain JSON is not an option.
编辑:除普通 JSON 之外的其他数据格式不是一种选择。
采纳答案by Sebastian Barth
JSON.stringifyindeed did the trick with two possible solutions:
JSON.stringify确实通过两种可能的解决方案做到了这一点:
a)The replacer function called to decide how to serialize a value.
a)调用替换函数来决定如何序列化一个值。
function replacer(key, value) {
if (typeof value === "string") {
return undefined;
}
return value;
}
var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = JSON.stringify(foo, replacer);
b)Define a toJSON()
member function for the object.
b)toJSON()
为对象定义一个成员函数。
var obj = {
foo: 'foo',
toJSON: function () {
return '{ "foo": "' + + '" }';
}
};
JSON.stringify(obj); // '{ "foo": "Zm9v" }'
Plz up thiscomment instead if that works for you, too.
PLZ了这个评论,而不是是否适合你。
回答by Joonas
For blobs it makes more sense to convert the Blobs in the object to base64 beforehand and then stringify the object. This is because there is no reliable way to synchronously convert a blob to base64.
对于 Blob,事先将对象中的 Blob 转换为 base64,然后对对象进行字符串化更有意义。这是因为没有可靠的方法将 blob 同步转换为 base64。
const blobToBase64 = (blob) => {
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
resolve(reader.result);
};
});
};
(async () => {
const b64 = await blobToBase64(blob);
const jsonString = JSON.stringify({blob: b64});
console.log(jsonString);
})();
Getting a blob from parsed JSON is then as simple as
从解析的 JSON 中获取 blob 就像这样简单
const parsed = JSON.parse(jsonString);
const blob = await fetch(parsed.blob).then(res => res.blob());
console.log(blob);