python - 使用烧瓶和本地 JSON 文件在 HTML 中显示 JSON
问题描述
我使用 Python 烧瓶、HTML 和本地 JSON 文件以在 HTML 中显示来自本地 JSON 文件的 JSON 数据。一旦烧瓶读取本地 JSON 文件,它就会通过 jsonify发送到index.html 。之后,使用该数据我想显示信息。
我可以在烧瓶端显示 JSON 数据,但在 HTML 中显示它时遇到了困难。你能告诉我我错过了什么吗?
烧瓶代码
import os
from flask import Flask, render_template, abort, url_for, json, jsonify
import json
import html
app = Flask(__name__)
# read file
with open('./data/file.json', 'r') as myfile:
data = myfile.read()
@app.route("/")
def index():
return render_template('index.html', title="page", jsonfile=jsonify(data))
app.run(host='localhost', debug=True)
索引.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
<title>House</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous"
/>
<script>
var jsonfile ={{jsonfile}};
</script>
</head>
<body>
<div class="container">
{{jsonfile}}
</div>
</body>
</html>
解决方案
您的问题是该jsonify
方法的使用。如果您阅读它的文档,jsonify
它会返回一个 Response 对象而不是一个字符串。所以你会得到这样的东西jsonify(data)
<Response 2347 bytes [200 OK]>
您可以删除jsonify
并json.dumps
改用,如下所示:
@app.route("/")
def index():
return render_template('index.html', title="page", jsonfile=json.dumps(data))
这对我有用。
推荐阅读
- python - 给定过去的时间戳,从这一刻开始找到下一个午夜
- android - 使用 Web API 连接 SQL Server 数据库和 Xamarin Android
- html - 使用带有把手(.hbs)的节点js时不显示图像
- javascript - 如何修改退出弹出窗口的cookie时间
- php - 如何在 php 和 zf2 中使用 ajax 为选项值创建过滤器
- windows-10 - openMP 环境设置
- database - ORM 是否应该为所有请求提供单个数据库连接?
- python - 创建新子类的语法糖?
- react-native - Flatlist 渲染空白空间
- python-3.x - Tkinter 框架未在按钮单击时显示