LoginSignup
3
6

More than 1 year has passed since last update.

Flask で JSON ファイルを読む

Last updated at Posted at 2017-06-14

次のプログラムの入力ソースを、MariaDB から JSON に変更。

flask で MariaDB を使う

フォルダー構成

json_read.py
templates/hello.html
templates/layout.html

json_read.py
# --------------------------------------------------------------------
#   json_read.py
#
#                       May/10/2019
#
# --------------------------------------------------------------------
from flask import Flask, render_template
import sys
import json

app = Flask(__name__)

@app.route('/')
def hello():
    name = "皆さんこんにちは"
    return name


@app.route('/json_pp')
def json_pp():
    file_json = "data/cities.json"
    fp_in = open (file_json,encoding='utf-8')
    json_str = fp_in.read()
    fp_in.close()
    dict_aa = json.loads(json_str)
#
    rows = []
    for key in sorted (dict_aa.keys()):
        unit = dict_aa[key]
        unit['id'] = key
        rows.append(unit)
#
    return render_template('hello.html', title='json', cities=rows)

#
if __name__ == "__main__":
    app.run(host='0.0.0.0',debug=True)
# --------------------------------------------------------------------
data/cities.json
{
  "t0921": {
    "name": "宇都宮",
    "population": 41295,
    "date_mod": "2003-8-12"
  },
  "t0922": {
    "name": "小山",
    "population": 38756,
    "date_mod": "2003-5-15"
  },
  "t0923": {
    "name": "佐野",
    "population": 71294,
    "date_mod": "2003-6-8"
  },
  "t0924": {
    "name": "足利",
    "population": 27138,
    "date_mod": "2003-7-21"
  },
  "t0925": {
    "name": "日光",
    "population": 74682,
    "date_mod": "2003-4-19"
  },
  "t0926": {
    "name": "下野",
    "population": 82951,
    "date_mod": "2003-10-14"
  }
}

クライアントは、

http://localhost:5000/json_pp

にアクセスする。

次のバージョンで確認しました。

$ flask --version
Python 3.10.1
Flask 2.0.2
Werkzeug 2.0.2
3
6
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
6