LoginSignup
3
3

More than 1 year has passed since last update.

Javascriptでローカルにある設定ファイル(json形式)を読み込む

Last updated at Posted at 2021-08-17

やりたいこと

ローカル上にあるJSON形式で書かれたファイルを読み込みJavascript上で扱えるようにする。

HTML

index.html
<input type="file" id="profile_form">

JavaScript

reader.ts
const profile_form = document.querySelector("#profile_form");
profile_form.addEventListener("change", (e) => {
  var profile = e.target.files[0];
  var data;
  var filename = profile.name;
  var type = profile.type;

  if (window.File && window.FileReader && window.FileList && window.Blob) {
    var reader = new FileReader();
    reader.readAsText(profile);
    reader.onload = (file) => {
      if (type == "application/json") {
        data = JSON.parse(file.target.result);
        console.log(data);
      } else {
      }
    };
  }
}, false);

reader.readAsText(profile)で指定されたファイルをテキスト形式で読み込む。
読み込まれたテキストはpromiseで帰ってくるのでreader.onloadで読み込み完了イベントをキャッチする。
JSON.parseで読み込んだテキストをJSON形式に直す。
dataにファイルの中身が格納される。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3