admin管理员组

文章数量:1414893

let file = new Blob([response.data], {type: 'application/json'});

response.data contains JSON file, I want to read the contents of this file and assign them as a JSON string to a variable in javascript.

I've tried a few things with FileReader.readAsText(file) but I'm not able to properly convert it into a simple JSON string.

P.S.: The response.data is an arraybuffer, so if there's a direct conversion that's possible without creating a Blob object, that should also solve the problem.

let file = new Blob([response.data], {type: 'application/json'});

response.data contains JSON file, I want to read the contents of this file and assign them as a JSON string to a variable in javascript.

I've tried a few things with FileReader.readAsText(file) but I'm not able to properly convert it into a simple JSON string.

P.S.: The response.data is an arraybuffer, so if there's a direct conversion that's possible without creating a Blob object, that should also solve the problem.

Share Improve this question edited May 3, 2022 at 7:38 Akshit Aggarwal asked May 3, 2022 at 7:12 Akshit AggarwalAkshit Aggarwal 591 silver badge7 bronze badges 3
  • try to create a new text file and add data – brk Commented May 3, 2022 at 7:13
  • Use await file.text() or file.text().then(jsonString => ...) – evolutionxbox Commented May 3, 2022 at 7:17
  • 1 It appears that you are trying to process a fetch response. And if is a json file then why not use Response.json? Or if you really want an array then use Response.arrayBuffer – Yogi Commented May 3, 2022 at 7:44
Add a ment  | 

1 Answer 1

Reset to default 4
let file = new Blob([response.data], {type: 'application/json'});

file.text()
        .then(value => {
           self.objectName = JSON.parse(value);
           console.log(self.objectName);
         })
         .catch(error => {
           console.log("Something went wrong" + error);
         });

Did the trick for me.

本文标签: How can I read a Blob object in Javascript as JSON objectStack Overflow