简体   繁体   中英

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

From a http request, a blob (b) (type application/octet-stream ) is downloaded and then needs to be processed, it contains a json object .

I tried the following:

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

It doesn´t work, and readResult is null.

How can you process a blob that contains a json into a json object?

You will need an onload event like so:

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

When the request has responseType: 'blob' it returns binary, but if an error occurs message is returned as JSON inside Blob.

This is how you can decode JSON messages from blob:

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

Code example :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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