3
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

【JavaScript】Blobの中身をJSONに変換する

JavaScriptでBlobの中身をJSONに変換したいことがあったため、方法のメモです。

以下のようなヘルパー関数を作ります。

/utils/fileReader.js
/**
 * 非同期にBlobをテキストとして読み込みます。
 */
export default blob => {
  const fileReader = new FileReader();

  return new Promise((resolve, reject) => {
    fileReader.onerror = () => {
      fileReader.abort();
      reject();
    };

    fileReader.onload = () => {
      resolve(fileReader.result);
    };

    fileReader.readAsText(blob);
  });
};

使用例

import fileReader from "/utils/fileReader";

const blobToJson = async blob => {
    const blobText = await fileReader(blob);
    return JSON.parse(blobText);
};
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
3
Help us understand the problem. What are the problem?