python でjsonデータをHTML変換する

先日jsonからHTML変換して見た目をわかりやすくする必要があったので、それの覚え書きです。

開発環境 MacOS Catalina, Python3

json_to_html.py

# coding:utf-8
import json
from collections import OrderedDict
from jinja2 import Environment, FileSystemLoader,Template

#HTMLテンプレートファイルの読み込み
env = Environment(loader=FileSystemLoader('./', encoding='utf8'))
tmpl = env.get_template('./templates/template.tmlp')

#JSON ファイルの読み込み
json_open = open('test.json', 'r')
#順番どおり読むにはOrderedDict が必要
json_load = json.load(open('test.json',encoding='utf-8'),object_pairs_hook=OrderedDict)

print (json.dumps(json_load,indent=2,ensure_ascii=False))

#HTML テンプレートに値をセットする
html = tmpl.render(json_to_html= json_load)

#HTML に書き込む(UTF-8にしないと文字化けする)
with open('json_to_html.html',mode='w',encoding='utf-8') as f:
    f.write(str(html))
    
print(html)

内容は適当です。

test.json

[
{
  "list_A": "タイトル1",
  "list_B": "東京",
  "list_C": "晴れときどき曇り",
  "list_D": "20%",
  "list_E": "本州付近は高気圧に覆われています。"
}
,{
  "list_A": "タイトル2",
  "list_B": "埼玉",
  "list_C": "晴れ",
  "list_D": "10%",
  "list_E": "高気圧に覆われますが、湿った空気の影響を受ける見込みです。このため、曇りで夜遅くは雨の降る所があるでしょう。 "
}
,{
  "list_A": "タイトル3",
  "list_B": "千葉",
  "list_C": "曇り",
  "list_D": "0%",
  "list_E": "高波に注意してください。 "
}
]

template.tmlp

<!DOCTYPE html>
<html lang="ja">
<head>
    <title>JSON to HTML</title>
    <link rel="stylesheet" href="./html/style.css">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>   
<div id="container">
<article id="contents">
  <h1 class="title-webdesign">JSON からHTML 作成テスト</h1>

<!--for文 でJSONを繰り返す-->
{% for i in json_to_html %}
  <ul class="list-webdesign">
<div><p class="link-title-wd">{{ i.list_A }}</p>
<p>都道府県:{{i.list_B}}</p>
<p>天気:{{i.list_C}}</p>
<p>降水確率:{{i.list_D}}</p>
<p>その他:{{i.list_E}}</p>
</div>
</ul>

{% endfor %}
</article>

<table>
{% for i in json_to_html %}

  <tr>
    <th>タイトル</th>
    <td>{{i.list_A}}</td>
  </tr>
  <tr>
    <th>都道府県</th>
    <td>{{i.list_B}}</td>
  </tr>
  <tr>
    <th>天気</th>
    <td>{{i.list_C}}</td>
  </tr>
  <tr>
    <th>降水確率</th>
    <td>{{i.list_D}}</td>
  </tr>
  <tr>
    <th>その他</th>
    <td>{{i.list_E}}</td>
  </tr>
{% endfor %}
</table>






</body>
</html>

実行方法

$ python3 json_to_html.py

私は旧世代の人間なので、print で出力確認しながらHTMLファイルを作成しています。

HTMLを開けばこんな感じになります。

CSS は適当です。

f:id:ruepon:20210211072810p:plain
出力例