見出し画像

"JSON"を使ってみよ。

JSONとはJavaScript Object Notationのこと。今現在、最もよく使われているデータフォーマットの一種です。JavaScriptとあるのですが、他の言語、Swift,Python,Javascripなどいろんな言語でデータの管理をする場合など使われています。

まずは形です。

{
   "name""太郎",
   "age"23,
}

要するに

key : value

辞書、連想配列と呼ばれるような形にしたものを" , " カンマで連ねていきます。

実際にどうやってJavaScriptでJSONを使ってみましょう!

データを別の形式に変換して使えるようにすることを、"デコード"と言います。

let json = '{"result": true, "count": 30}';
let obj = JSON.parse(json);
console.log(obj.result);
console.log(obj.count);

とすると

true
30

と出力されます。

let json = '{"result": true, "count": 30}';

これがJSONです。

パース(解析)します。

let obj = JSON.parse(json);

パースしたものを変数 "obj"に入れます。そして出力します。

console.log(obj.result);
console.log(obj.count);

値を取り出します。

変数obj に代入している連想配列を呼び出します。obj に続いて" . " で繋ぎます。例えば obj.result とすると、配列の

"result": true

部分が呼び出され、"result"に対応するTrueが帰ってきます。

JavaScript WEB APIを扱ってみます。

HTML

<!DOCTYPE html> 
<html lang="ja">
<head>
 <meta charset="utf-8">
 <title>わんわんお</title>
 <link rel="stylesheet" href="css/styles.css">
</head>
<body>
 <button id='click'>わんわんお?</button>
 <!-- APIから取得した犬種と画像を表示する -->
 <div>犬種:<span id='type'></div>
 <div>画像:<img id='image'></div>
 <script src="js/main.js"></script>
</body>
</html>

に対しJavaScriptは

const button = document.getElementById('click');
   const type = document.getElementById('type');
   const image = document.getElementById('image');
   // ボタンをクリックしたらイベント発動
   button.addEventListener('click', () => {
       fetch('https://dog.ceo/api/breeds/image/random') // APIのURL
       .then(response => {
           return response.json();
       })
       .then(myJson => {
           // imgタグに取得したURL画像を入れる
           image.src = myJson['message'];
           // 取得したURLをスラッシュ記号で分割し、犬種を表した要素を取得する
           const breed = myJson['message'].split('/')[4];
           type.innerText = breed;
           button.innerText = 'わんわんお!'
       });
   });

です。

画像が映し出されます。


続いてPythonでJSON APIを使ってみます。

import json
import urllib.request
try:
   url = 'https://www.craneto.co.jp/study_sample/simple_json_file.json'
   res = urllib.request.urlopen(url)
   # json_loads() でPythonオブジェクトに変換
   data = json.loads(res.read().decode('utf-8'))
   print(data['title'])
   print(data['author'])
   print(data['description'])
   for item in data['pages']:
       print(item['title'], ':', item['url'])
except urllib.error.HTTPError as e:
   print('HTTPError: ', e)
except json.JSONDecodeError as e:

出力は

サンプルJSON
Crane & to.株式会社
JSONの学習用サンプルファイルです。サンプルのため内容に特に意味はありません。
トップページ : https://www.craneto.co.jp/
スタッフブログ : https://www.craneto.co.jp/archives/category/all/
サービス紹介 : https://www.craneto.co.jp/services/

となります。

まずインポートするとこから始まります。

import json
import urllib.request

そして"url"を指定して使えるようにします。

   url = 'https://www.craneto.co.jp/study_sample/simple_json_file.json'
   res = urllib.request.urlopen(url)

最後にパース!解析します。

 data = json.loads(res.read().decode('utf-8'))

そして出力していきます。

ここでは、try文とexcept節を使っています。Pythonの例外処理です。

この記事が気に入ったらサポートをしてみませんか?