【问题标题】:How to read Blob (octet-stream) to JSON object?如何将 Blob(八位字节流)读取到 JSON 对象?
【发布时间】:2019-08-12 13:32:20
【问题描述】:

从一个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 对象?

【问题讨论】:

标签: javascript json blob


【解决方案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);

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      代码示例:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-19
        • 1970-01-01
        • 2020-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多