Flask で JSON ファイルを読む

  • 1
    Like
  • 0
    Comment

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

http://qiita.com/ekzemplaro/items/a5e38772e0fa94323da6

フォルダー構成

json_read.py
template/hello.html
template/template.html

json_read.py
# --------------------------------------------------------------------
#   json_read.py
#
#                       Jun/14/2017
#
# --------------------------------------------------------------------
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(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

にアクセスする。