JSONデータの扱い方/Web APIの利用
(ブログ記事の一覧は「こちら」)
JSON(JavaScript Object Notation)とは、データを定義するためのフォーマットの1つです。同じような考えのフォーマットとして他にはXMLやCSVがあります。JSONは、その名前の通りJavaScriptでデータをパース(解析)するのに適しています。
最近では、Web APIの実行結果でよく使われるフォーマットとしては、JSONが多く見られます。ここでは、JSONフォーマットを出力するWeb APIの例として、天気情報/予報API「OpenWeatherMap API」を試します。
準備
まずはOpenWeatherMap のサイトにアクセスして、右上の「Sign Up」からユーザー登録を行ってください。(無料)
登録が完了すると、APIを利用するための「App ID」が作成されます。
例えば、以下のURLにアクセスすると、現在の東京の天気情報を受け取ることができます。(最後の xxxx ... の部分は、登録時に取得した「App ID」を入力します。)
https://api.openweathermap.org/data/2.5/weather?q=Tokyo&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
また、OpenWeatherMapでは天気の画像が用意されています。以下のリンクを参照してください。
https://openweathermap.org/weather-conditions
「快晴(clear sky)」を取得する場合は、以下のURLになります。
https://openweathermap.org/img/wn/01d@2x.png
imgタグのsrcに上のURLをセットすることで表示することができます。
OpenWeatherMap APIによる、天気情報の出力結果の例
現在の東京の天気情報の、出力結果の例です。
{ "coord": { "lon": 139.76, "lat": 35.68 }, "weather": [ { "id": 801, "main": "Clouds", "description": "few clouds", "icon": "02d" } ], "base": "stations", "main": { "temp": 283.95, "feels_like": 278.39, "temp_min": 282.04, "temp_max": 287.04, "pressure": 1025, "humidity": 39 }, "visibility": 10000, "wind": { "speed": 4.6, "deg": 360 }, "clouds": { "all": 20 }, "dt": 1578278882, "sys": { "type": 1, "id": 8074, "country": "JP", "sunrise": 1578261066, "sunset": 1578296472 }, "timezone": 32400, "id": 1850147, "name": "Tokyo", "cod": 200 }
サンプルプログラム
上記の、出力結果の例にあるJSONデータをもとに、表示したいデータを取得します。
まずは、index.htmlを作成します。(後の、JavaScriptとjQueryの共通で使用できます)
<html> <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="main.js"></script> </head> <body> <h1>OpenWeatherMap API</h1> <p>場所:<span id="place"></span></p> <p>天気:<span id="weather"></span></p> <p><span id="description"></span></p> <p><img id="icon"></p> <p>気温:<span id="temp"></span>℃</p> <p>湿度:<span id="humidity"></span>%</p> </body> </html>
main.jsを作成します。JavaScript, jQueryそれぞれの記述例は同じ内容です。
JavaScriptでの記述例
var strUrl = "https://api.openweathermap.org/data/2.5/weather?q=Tokyo&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { // 非同期通信(Ajax) // readyState 4: リクエスト終了, status 200:通信成功 if (this.readyState == 4 && this.status == 200) { var data = this.response; // 場所 document.getElementById('place').innerHTML = data.name; // 天気(画像) var img = document.getElementById('icon'); img.src = "https://openweathermap.org/img/wn/" + data.weather[0].icon + "@2x.png"; img.alt = data.weather[0].main; // 天気 document.getElementById('weather').innerHTML = data.weather[0].main; document.getElementById('description').innerHTML = data.weather[0].description; // 気温 document.getElementById('temp').innerHTML = Math.floor((data.main.temp - 273.15) * 100) / 100; // 湿度 document.getElementById('humidity').innerHTML = data.main.humidity; } } xmlhttp.open("GET", strUrl, true); xmlhttp.responseType = 'json'; // JSONを取得するために必要 xmlhttp.send();
jQueryでの記述例
$.ajax({ type: "GET", url: "https://api.openweathermap.org/data/2.5/weather?q=Tokyo&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }).done(function(data) { // 場所 $("#place").html(data.name); // 天気(画像) var img = $("#icon"); img.attr("src", "https://openweathermap.org/img/wn/" + data.weather[0].icon + "@2x.png"); img.attr("alt", data.weather[0].main); // 天気 $("#weather").html(data.weather[0].main); $("#description").html(data.weather[0].description); // 気温 $("#temp").html(Math.floor((data.main.temp - 273.15) * 100) / 100); // 湿度 $("#humidity").html(data.main.humidity); }).fail(function(data) { alert("error"); });
課題1
index.htmlにボタンを3個追加して、クリックすると「Tokyo」「Osaka」「XXX(あなたの生まれた場所)」に天気情報の表示が切り替わるような仕組みになるように改造してください。
以下を参考にしてください。
... <p><input type="button" value="Tokyo" onclick="callOpenWeatherMap('Tokyo')"></p> ...
main.jsは、関数化する必要があります。
function callOpenWeatherMap(place) { var strUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + place + "&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 以下、カスタマイズ }
課題2
以下のURLにアクセスすると、東京の天気予報の情報を受け取ることができます。
(最後の xxxx ... の部分は「App ID」を入力します。)
https://api.openweathermap.org/data/2.5/forecast?q=Tokyo&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
得られた結果のJSONデータを分析して、見やすい天気予報のWebページを作成してください。
また、東京以外の複数の場所を選択して表示を切り替えることができるようにしてください。