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

时间:2019-03-21 16:10:53

标签: javascript json blob

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

我尝试了以下操作:

var reader = new FileReader();
reader.readAsText(b);
var readResult = <string> reader.result;
console.log(readResult);
var obj = JSON.parse(readResult);

它不起作用,并且readResult为null。

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

3 个答案:

答案 0 :(得分:1)

您将需要一个 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);

答案 1 :(得分:0)

当请求具有 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
  }
}

答案 2 :(得分:-1)

代码示例:

try{
      await this.exampleservice.MygetRequest().then(httpResponse => {
        httpResponse.body.text().then(text => {
          //console.log(text);
          obj = JSON.parse(text);
          //console.log('obj after parse:' ,obj);
          let data = obj.result.data; 
          console.log('My data:' ,data);
        });
    });
    }catch (error) {
      if (error instanceof HttpErrorResponse) {
        Swal({
          type: 'error',
          title: this.errorsService.getErrorMessage(error.status),
          showConfirmButton: false,
          timer: 1500
        });
        this.feedback_errors = error.error.errors;
        this.feedback_errors_keys = this.feedback_errors ? Object.keys(this.feedback_errors) : null;
      } 
    }