正在将 JSON 从 Python 加载到 Google 个图表 PHP/HTML

Loading JSON from Python into Google Charts PHP/HTML

我想在 Google 图表的 PHP 代码中包含从 py 文件生成的 JSON 字符串。

为了生成 JSON 字符串,我遵循了:https://developers.google.com/chart/interactive/docs/dev/gviz_api_lib 代码将这样结束:

# Create a JavaScript code string.
jscode_output = data_table.ToJSCode("jscode_data",
                               columns_order=("number", "link quality"),
                               order_by="number")
# Create a JSON string.
json_output = data_table.ToJSon(columns_order=("number", "link quality"),
                           order_by="number")

然后我将py文件保存为script.py

接下来我使用Google图表折线图代码:

  <html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance',
          curveType: 'function',
          legend: { position: 'bottom' }
        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>
  </body>
</html>

问题:现在如何将 script.py 文件和 json 变量集成到这段代码中?根据我的理解,var 数据行需要更改为此 - 但我不确定这是否正确:

var data = google.visualization.arrayToDataTable(json)

我如何 运行 py 脚本?我想 运行 所有这些代码作为 PHP 以在(本地)网站上显示它,但我不确定最安全的方法是 运行 html/php.

中的 py 脚本

现在这对我有用。花了很多时间在上面,因为我无法在网上找到适合初学者的综合示例:

  1. 将 py 文件保存为 JSON 文件:
with open("output.json", "w") as text_file:
    print(json_output, file=text_file)

这里之前创建的json_output不必重新编码成json,因为它已经是正确的格式,所以我只是将它保存为文本文件。

  1. 创建调用 JSON 文件的 PHP 文件:
<?php
$string = file_get_contents("output.json");
echo $string;
?>
  1. 修改google图表函数如下:
    function drawChart() {
      
      //Call JSON output from php file
      var jsonData = $.ajax({
          url: "test_phpfile.php", 
          dataType: "json",
          async: false
          }).responseText;

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(jsonData);
      var options = {
                title: 'Test Chart',
                curveType: 'function'
              }
      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data,options);
    }

而不是 运行 php 中的 py 文件(还不知道该怎么做)我现在安排 py 文件每隔一段时间生成一个 JSON 文件[15]分钟。很高兴知道这方面的最佳做法是什么 - 最终我只想在本地网站上显示此图表。