5

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?

3

3 Answers 3

6

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
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This won't work in chrome if the blob is >=.5Gb, since it's impossible to create a string that big.
4

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.