【问题标题】:JSON.stringify or how to serialize binary data as base64 encoded JSON?JSON.stringify 或如何将二进制数据序列化为 base64 编码的 JSON?
【发布时间】:2015-01-29 16:58:08
【问题描述】:

我有一个 Javascript 对象,它将由一个带有参数和子对象的非循环对象层次结构组成。其中一些对象可能包含从文件加载或通过 XHR 接收的二进制数据(如果 Blob、ArrayBuffer 或其他对象尚未定义)。

通常我会使用 JSON.stringify() 将其序列化为 JSON,但我如何指定二进制数据将采用 base64 编码?

那么你会推荐我什么二进制数据对象(Blob、ArrayBuffer、...)?

编辑:除了纯 JSON 之外的其他数据格式不是一个选项。

【问题讨论】:

标签: javascript json blob arraybuffer


【解决方案1】:

对于 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);
})();

从解析的 JSON 中获取 blob 就像

const parsed = JSON.parse(jsonString);
const blob = await fetch(parsed.blob).then(res => res.blob());
console.log(blob);

【讨论】:

    【解决方案2】:

    JSON.stringify 确实使用了两种可能的解决方案:

    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)为对象定义一个toJSON()成员函数。

    var obj = {
      foo: 'foo',
      toJSON: function () {
        return '{ "foo": "' +  + '" }';
      }
    };
    JSON.stringify(obj);      // '{ "foo": "Zm9v" }'
    

    如果这也适合你,请留言 this

    【讨论】:

    • 这是如何回答问题的?
    • 那么base64在哪里进入你的解决方案?
    猜你喜欢
    • 2014-11-06
    • 1970-01-01
    • 2013-01-26
    • 2011-09-17
    • 2011-11-02
    • 2017-07-14
    • 2016-09-21
    • 2012-11-09
    • 1970-01-01
    相关资源
    最近更新 更多