gpt4 book ai didi

python - Pandas 数据框到 flask 模板作为 json

转载 作者:行者123 更新时间:2023-12-03 15:49:32 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





JavaScript raises SyntaxError with data rendered in Jinja template

(3 个回答)


4年前关闭。




我尝试在 flask 模板中输出 Pandas 数据框。我的想法是将其转换为 json 然后循环遍历表

我测试了这个

jsonfiles = df.to_json(orient='records')

return render_template('index.html', ctrsuccess=jsonfiles)

在模板中,我尝试像这样输出:
        {%if ctrsuccess %}
<div class="table-responsive">
<table class="table table-striped">
<tbody>
{%for ctrrow in ctrsuccess %}
<tr>
<td>{{ ctrrow['positionint'] }}</td>
</tr>
{%endfor%}
</tbody>
</table>
</div>
{%endif%}

在模板中,如果我只是绘制 ctrsuccess,我会得到一个外观正确的 json。但是 table 是空的
[{"positionint":1.0,"clicks":1138.0,"impressions":4768.0,"ctr":0.2386744966,"clickCtr10p":1251.8,"clickCtr50p":1707.0,"clickCtr100p":2276.0},{"positionint":2.0,"clicks":3160.0,"impressions":49899.0,"ctr":0.0633279224,"clickCtr10p":3476.0,"clickCtr50p":4740.0,"clickCtr100p":6320.0},{"positionint":3.0,"clicks":1255.0,"impressions":50020.0,"ctr":0.025089964,"clickCtr10p":1380.5,"clickCtr50p":1882.5,"clickCtr100p":2510.0},{"positionint":4.0,"clicks":363.0,"impressions":39077.0,"ctr":0.0092893518,"clickCtr10p":399.3,"clickCtr50p":544.5,"clickCtr100p":726.0},{"positionint":5.0,"clicks":216.0,"impressions":18419.0,"ctr":0.011727021,"clickCtr10p":237.6,"clickCtr50p":324.0,"clickCtr100p":432.0},{"positionint":6.0,"clicks":307.0,"impressions":15447.0,"ctr":0.0198744093,"clickCtr10p":337.7,"clickCtr50p":460.5,"clickCtr100p":614.0},{"positionint":7.0,"clicks":248.0,"impressions":24709.0,"ctr":0.0100368287,"clickCtr10p":272.8,"clickCtr50p":372.0,"clickCtr100p":496.0},{"positionint":8.0,"clicks":236.0,"impressions":26853.0,"ctr":0.0087885897,"clickCtr10p":259.6,"clickCtr50p":354.0,"clickCtr100p":472.0},{"positionint":9.0,"clicks":139.0,"impressions":26577.0,"ctr":0.0052300862,"clickCtr10p":152.9,"clickCtr50p":208.5,"clickCtr100p":278.0},{"positionint":10.0,"clicks":23.0,"impressions":2046.0,"ctr":0.0112414467,"clickCtr10p":25.3,"clickCtr50p":34.5,"clickCtr100p":46.0},{"positionint":null,"clicks":7085.0,"impressions":257815.0,"ctr":null,"clickCtr10p":7793.5,"clickCtr50p":10627.5,"clickCtr100p":14170.0},{"positionint":null,"clicks":null,"impressions":null,"ctr":null,"clickCtr10p":1417.0,"clickCtr50p":7085.0,"clickCtr100p":14170.0}]

最佳答案

根据 Pandas 文档,to_json呈现一个 json 字符串,您可以使用 type(jsonfiles) 进行确认.虽然打印输出看起来像一个 json 对象,但单引号会在开头和结尾换行。

要解决,只需导入内置的json模块(Python 标准库的一部分)并解析 to_json使用 loads 将字符串转换为 json 对象方法:

import json
...

jsonfiles = json.loads(df.to_json(orient='records'))

return render_template('index.html', ctrsuccess=jsonfiles)

关于python - Pandas 数据框到 flask 模板作为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48050769/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com