LoginSignup
20
14

More than 3 years have passed since last update.

JavaScriptのfetch APIでjsonをfetchしてみる。

Last updated at Posted at 2018-08-06

はじめに

電車の遅延情報を使って遊ぼうと思って、下記サイトを知った。
JavaScriptでjsonゲットして表示させようと思って調べたら、最近はfetchっての使うらしいことがわかったので、試してみた。

鉄道遅延情報のjson

コード

HTMLはこんな感じ。
jQueryは使わない。

train_delay.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Train delay!</title>
  </head>
  <body>
    Train delay!
    <script src="train_delay.js">
    </script>
  </body>
</html>

JavaScriptはこんな感じ。fetchして、気になる路線が載ってたらconsole.log()する。

train_delay.js
var url_delay = "https://rti-giken.jp/fhc/api/train_tetsudo/delay.json";

fetch(url_delay)
    .then(function(response) {
        return response.json();
    })
    .then(function(myJson) {
        // console.log(myJson);                                                      
        // console.log(myJson.length);                                               
        for (var i=0; i<myJson.length; i++) {
            if(myJson[i].name == "中央線"){
                console.log("遅延しています");
                return true;
            }
        }
        console.log("遅延していません");
        return false;
    });

結果

結果はこんな感じ。全然面白みないけども。

image.png

おわりに

いまいちピンと来てないまま試してたので、時間がかかった。
なれない文法なので、不思議な感じ。最近はこんなふうに書くんかな?もっと勉強が必要そう。

参考

Google Apps Scriptから色んな鉄道の遅延情報を取得する - Androidのメモとか

Fetch 概説 - Web API インターフェイス | MDN

20
14
2

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
20
14