3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScript: ローカルのJSからfetch APIでGETしたJSONをFileSaver.jsを使ってファイルに保存する

Last updated at Posted at 2019-08-19

ローカルでfetchを使うにはCORS対応が一工夫必要なので、下記の記事を参考までにどうぞ
Qiita - ローカルのHTMLファイルでfetchを試す & CORSとその回避策

やりたいこと

  • ローカルのJSからfetch APIを使って公開APIを叩き、GETしたJSONをファイルに保存する
  • FileSaver.jsというnpmのパッケージをnode.jsとかの無いローカル環境で動かしてみる

FileSaver.js

コード

test.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script type="text/javascript" src="FileSaver.js"></script>
  </head>
  <body>
    <input type="button" value="取得" onclick="apiRequest()" />
    <div id="export"></div>
    <script>
      async function apiRequest() {
        const downloadUrl =
          "http://zipcloud.ibsnet.co.jp/api/search?zipcode=1620825";
        const response = await fetch(downloadUrl);
        const blob = response.blob();
        const fileName = "test.json";
        saveAs(blob, fileName);
      }
    </script>
  </body>
</html>

ファイルの中身

test.json
{
	"message": null,
	"results": [
		{
			"address1": "東京都",
			"address2": "新宿区",
			"address3": "神楽坂",
			"kana1": "トウキョウト",
			"kana2": "シンジュクク",
			"kana3": "カグラザカ",
			"prefcode": "13",
			"zipcode": "1620825"
		}
	],
	"status": 200
}

まとめ

  • 簡単だった
  • 今度何やろう
3
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?