Pandas数据框作为json的烧瓶模板

时间:2018-01-01 15:13:48

标签: python json pandas flask

我尝试在刻录模板中输出pandas数据帧。我的想法是将它转换为json,然后循环遍历表

我测试了这个

index

在模板中我尝试输出如下:

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

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

在模板中,如果我只是绘制ctrsuccess,我会得到一个正确的json。但表格是空的

        {%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%}

1 个答案:

答案 0 :(得分:6)

根据每个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)