How can I read a Blob object in Javascript as JSON object - Stack Overflow

let file = new Blob([response.data], {type: 'applicationjson'});response.data contains JSON

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745183965a4615548.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信