javascript - flask +d3.js : Passing multiple datasets to html

标签 javascript python json d3.js

我目前正在学习用于可视化的 d3.js,使用 Flask 作为 python 后端,并关注 this example在同一页面上显示两个具有不同数据集的简单图表。

我正在尝试进行以下修改:我不想使用 CSV,而是想从 python 后端传递一个 json 文件(该示例只是从两个 csv 文件中读取数据)。我如何传递 2 个 json 数据集?我可以按如下方式传递一个:

Python 后端

import flask...

app = flask.Flask(__name__)

@app.route("/")
def index():
    return flask.render_template("index.html")

@app.route("/data")
def data():
    x = [1, 2, 3, 4, 5]
    y = [1, 2, 3, 4, 5]
    js = [{"x":x[i], "y":y[i]} for i in range(len(x))]

    return json.dumps(js)

index.html

<script>
d3.json("/data", function(data) ...)
</script>

我尝试编写另一个 python 函数,例如 def data_bar 以返回一个单独的 json 数据集,但无法读取。理论上,我可以在一个 json 数据集中传递两个数据集,例如:

x = [1,2,3,4,5]
y = [1,2,3,4,5]
x1 = [10,20,30]
y1 = [40,50,60]

但是如果第一组(x 和 y)和第二组(x1 和 y1)的域不相同,就会遇到问题。例如第一组可以是“student_name”和“grade”,第二组可以是“class_name”和“average_grade”。

最佳答案

渲染一个传入的数据集:

return render_template("result.html",resultVarInHtml = myData)

使用传入的多个数据集进行渲染:

return render_template("result.html",resultVarInHtml = myData, resultVarInHtml2 = myData2)

现在当我加载 result.html

我可以使用这段代码来显示我的数据(假设是一个键值字典对象,但你明白了)

结果.html

<!doctype html>
<html>
   <body>
   <p>First Data Set</p>
      <table border = 1>
         {% for key, value in resultVarInHtml.iteritems() %}

            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>

         {% endfor %}
      </table>
      <p>2nd Data Set</p>
      <table border = 1>
         {% for key, value in resultVarInHtml2.iteritems() %}

            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>

         {% endfor %}
      </table>
   </body>
</html>

你会得到一张合适的 table ,伙计。

关于javascript - flask +d3.js : Passing multiple datasets to html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42617544/

相关文章:

javascript - 顺风暗: is not working on next. js?

python - 区分元组和元组的元组

ios - 将 Codable 结构编码为 JSON 后如何存储数据

javascript - 函数作为参数没有在原型(prototype)中定义但仍然可以传入?

javascript - 根据另一个中的选择填充一个下拉列表

javascript - 在 webgl 和 opengles 中渲染带有反射的三 Angular 形网格的问题

python - 将 2x2 DataFrame 整理成 4x1 系列 (Pandas)

python - 如何减少 python-docx 中段落之间的间距

PHP & MySQL : Query from 2 tables

javascript - 过滤和排序 JSON 格式的对象?