如何将 Blob(八位字节流)读取为 JSON 对象?

Mar*_* M. 5 javascript json blob

从http请求中,下载一个blob(b)(类型application/octet-stream ),然后需要进行处理,它包含一个json对象

\n\n

我尝试了以下方法:

\n\n
var reader = new FileReader();\nreader.readAsText(b);\nvar readResult = <string> reader.result;\nconsole.log(readResult);\nvar obj = JSON.parse(readResult);\n
Run Code Online (Sandbox Code Playgroud)\n\n

它不起作用,\xc2\xb4t 工作,并且 readResult 为空。

\n\n

如何将包含 json 的 blob 处理为 json 对象?

\n

kee*_*mor 6

当请求的responseType: 'blob' 时,它返回二进制,但如果发生错误,消息将以 Blob 内的 JSON 形式返回。

这是从 blob 解码 JSON 消息的方法:

(response) => {
  return response;
},
async (error) => {
  if (error.response.data instanceof Blob) {
    const blob = new Blob([error.response.data]);
    const data = await blob.text();
    const { message, details } = JSON.parse(data);
    //display message and details to the user
  }
}
Run Code Online (Sandbox Code Playgroud)


Pri*_*kar 4

您将需要一个像这样的onload事件:

var blob = new Blob([JSON.stringify({"test": "Hello from JSON!"})], {type : "application/json"}),
    reader = new FileReader();

reader.onload = function() {
    document.body.innerText = JSON.parse(this.result).test;
};

reader.readAsText(blob);
Run Code Online (Sandbox Code Playgroud)