繁体   English   中英

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

[英]How to read Blob (octet-stream) to JSON object?

从 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 为空。

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

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

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

代码示例:

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;
      } 
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM