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?

Marie M.
  • 170
  • 1
  • 3
  • 13
  • 1
    `readAsText` is asynchronous. You need to listen to the `loadend` event. See https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsText –  Mar 21 '19 at 16:12
  • Possible duplicate of [FileReader.result return null](https://stackoverflow.com/questions/28658388/filereader-result-return-null) –  Mar 21 '19 at 16:13
  • Another possible duplicate of https://stackoverflow.com/questions/11829537/html5-filereader-how-to-return-result –  Mar 21 '19 at 16:14

3 Answers3

5

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
  }
}
keemor
  • 1,149
  • 15
  • 16
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);
Priyesh Diukar
  • 2,032
  • 1
  • 15
  • 19
-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;
      } 
    }