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

3

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?

Dreadnought answered 21/3, 2019 at 16:10 Comment(3)
readAsText is asynchronous. You need to listen to the loadend event. See developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsTextCitrate
Possible duplicate of FileReader.result return nullCitrate
Another possible duplicate of #11830037Citrate
A
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);
Acetate answered 21/3, 2019 at 16:22 Comment(0)
D
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
  }
}
Dendro answered 1/7, 2021 at 13:22 Comment(1)
This won't work in chrome if the blob is >=.5Gb, since it's impossible to create a string that big.Criticize
A
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);
Acetate answered 21/3, 2019 at 16:22 Comment(0)
L
-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;
      } 
    }
Loaning answered 20/12, 2020 at 19:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.