Mar*_* M. 5 javascript json blob
从http请求中,下载一个blob(b)(类型application/octet-stream ),然后需要进行处理,它包含一个json对象。
\n\n我尝试了以下方法:
\n\nvar reader = new FileReader();\nreader.readAsText(b);\nvar readResult = <string> reader.result;\nconsole.log(readResult);\nvar obj = JSON.parse(readResult);\nRun Code Online (Sandbox Code Playgroud)\n\n它不起作用,\xc2\xb4t 工作,并且 readResult 为空。
\n\n如何将包含 json 的 blob 处理为 json 对象?
\n当请求的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)
您将需要一个像这样的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)
| 归档时间: |
|
| 查看次数: |
24188 次 |
| 最近记录: |