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

How do I get JSON data when the key has spaces in it using python and flask?

我使用的是昆士兰政府 API。它的格式是JSON,键中有空格。我正在尝试使用 python 和烧瓶访问它们。我可以传递 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代码

The error that is shown on the webpage when trying to load it.

有什么建议吗?

jinja2 中(Flask 将其用于模板化),您可以像在 python 中一样访问字典元素,请考虑以下示例:

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

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

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

希望这能解决您的问题!