JSON.stringify or how to serialize binary data as base64 encoded JSON?

♀尐吖头ヾ 提交于 2019-12-10 17:23:52

问题


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).

Normally I would use JSON.stringify() to serialize it as JSON but how can I then specify that binary data will be base64 encoded?

What binary data object (Blob, ArrayBuffer,...) would you recommend me then?

EDIT: Other data formats than plain JSON is not an option.


回答1:


JSON.stringify indeed did the trick with two possible solutions:

a) The replacer function called to decide how to serialize a value.

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.

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

Plz up this comment instead if that works for you, too.



来源:https://stackoverflow.com/questions/27232604/json-stringify-or-how-to-serialize-binary-data-as-base64-encoded-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!