# JSON

JSONはJavaScriptのオブジェクト(≒辞書型)を参考に作られたデータフォーマット(データの記述形式)です。

JavaScriptだけではなくPythonやPHP、C++、Javaなどの様々な言語でサポオートされており、人間にとってわかりやすく機械にとっても容易に解読(パース)、生成ができることが特徴です。

JSONはPythonの標準ライブラリなためインポートして使用します。

# JSONコード例

import json

# 文字列にするために'''を使用
sample_json = '''
{
    "name": "John",
    "age": 30,
    "city": "New York"
}
'''

# JSONを辞書形式に変換
parsed_dict = json.loads(sample_json)
print(parsed_dict)
import json

sample_dict = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# 辞書をJSONに変換
json_data = json.dumps(sample_dict)
print(json_data)

それぞれの出力は、以下のようになります

{'name': 'John', 'age': 30, 'city': 'New York'}
{"name": "John", "age": 30, "city": "New York"}

このように、辞書は'(シングルクォーテーション)、JSONは"(ダブルクオーテーション)で表記します。

# 演習6-1-1

以下のJSONから、駅名と路線を取得して出力せよ。

解答形式は["station_name":"駅名","lines":["路線1","路線2"]]とする。

{
  "railway_network": "JR東日本",
  "stations": [
    {
      "station_name": "東京駅",
      "location": {
        "latitude": 35.6812,
        "longitude": 139.7671
      },
      "lines": ["東海道本線", "中央本線"],
      "facilities": {
        "ticket_gate": true,
        "escalator": true,
        "restrooms": {
          "male": true,
          "female": true
        }
      }
    },
    {
      "station_name": "新宿駅",
      "location": {
        "latitude": 35.6895,
        "longitude": 139.7009
      },
      "lines": ["中央線", "山手線"],
      "facilities": {
        "ticket_gate": true,
        "elevator": true,
        "restrooms": {
          "male": true,
          "female": true
        }
      }
    },
    {
      "station_name": "横浜駅",
      "location": {
        "latitude": 35.4643,
        "longitude": 139.6225
      },
      "lines": ["東海道本線", "横浜線"],
      "facilities": {
        "ticket_gate": true,
        "escalator": true,
        "elevator": true,
        "restrooms": {
          "male": true,
          "female": true
        }
      }
    }
  ]
}