当密钥中有空格时,如何使用python和flask获取JSON数据



我使用的是昆士兰政府API。它的格式是JSON,键中有空格。我正试图用python和flask访问它们。我可以将所需的数据传递到HTML文件,但不能使用flask打印它。

{% block content %}
<div>
{% for suburb in data %}
<p>{{ suburb.Age }}</p>
<p>{{ suburb.Manslaughter Unlawful Striking Causing Death }}</p>
{% endfor %}
</div>
{% endblock content %}

上面是HTML文件的代码"杀人罪非法袭击致人死亡;是我试图访问的密钥,但在加载页面时会出现此错误。

from flask import Flask, render_template
import requests
import json
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
req = requests.get("https://www.data.qld.gov.au/api/3/action/datastore_search?resource_id=8b29e643-56a3-4e06-81da-c913f0ecff4b&limit=5")
data = json.loads(req.content)
print(data)
district=[]
for Districts in data['result']['records']:
district.append(Districts)
return render_template('index.html', data=district)

if __name__=="__main__":
app.run(debug=True)

上面是我正在运行的所有python代码。

尝试加载时网页上显示的错误。

有什么建议吗?

您可以访问像这样的字典中的值,而不是在模板中使用点表示法

{{ suburb['Manslaughter Unlawful Striking Causing Death'] }}

希望这能解决你的问题!

jinja2(Flask用于模板(中,您可以访问类似于python中的dict元素,请考虑以下示例:

import jinja2
temp = jinja2.Template("Value of abc is {{data['a b c']}}")
data = {'a b c': '1 2 3'}
rend = temp.render(data=data)
print(rend)

输出

Value of abc is 1 2 3

最新更新