Flask的jinja输出json内容

结构如下:

├── hello.py
├── Stats.json
└── templates
    └── index.html
 

实验步骤

python hello.py

浏览器打开:

127.0.0.1:5000

页面输出结果为:

#-----------------------------------------------------------------------------------

index.html

<table>
    <tr>
        <th>first_name</th>
        <th>last_name</th>
        <th>user_id</th>
        <th>address</th>
    </tr>
{% for i in data %}
    <tr>
        <td>{{ i.first_name }}</td>
        <td>{{ i.last_name }}</td>
        <td>{{ i.user_id}}</td>
        <td>{{ i.address}}</td>
    </tr>
{% endfor %}
</table>

Stats.json

[
    {
        "first_name": "John",
        "last_name": "Smith",
        "user_id": 4,
        "address": null
    },
    {
        "first_name": "Jane",
        "last_name": "Heart",
        "user_id": 5,
        "address": null
    },
    {
        "first_name": "Dom",
        "last_name": "Robinsons",
        "user_id": 6,
        "address": null
    },
    {
        "first_name": "Pete",
        "last_name": "Hand",
        "user_id": 7,
        "address": null
    }
]

hello.py

import json
from flask import render_template
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    jsonFile = open("Stats.json", "r")  # Open the JSON file for reading
    data = json.load(jsonFile)  # Read the JSON into the buffer
    jsonFile.close()  # Close the JSON file
    return render_template('index.html', data= data)

if __name__ == '__main__':
    app.run(debug=True)
发布了785 篇原创文章 · 获赞 357 · 访问量 166万+

猜你喜欢

转载自blog.csdn.net/appleyuchi/article/details/105058441
今日推荐