如何修复编码错误的JSON数据以在实时谷歌图表中使用



我在网站上的一个页面上使用烧瓶和谷歌图表。我有一个页面显示数据库的最后一行,该数据库采用 json 对象格式,如下所示:

{"temperature": 11.0, "datetime": "12-12-12 23-23-23"}

在烧瓶中,我正在制作这个getjson页面,如下所示:

@app.route('/getjson')
def getjson():
    tempdata = getTemperatureData()
    return render_template('getjson.html', **locals())

这会将局部变量 tempdata 传递给它。在此之后,我用简单的代码制作了一个html文件(getjson.html

(:
{{tempdata}}

当我加载网页并签入检查元素选项卡时,我得到的看起来像 pythonanywhere 或 flask 添加了所有这些 html 数据:

<html>
    #shadow-root (open)
    <head></head>
    <body>{"temperature": 11.0, "datetime": "12-12-12 23-23-23"}</body>
</html>
我的

问题是我的谷歌图表无法加载,它似乎在我的浏览器的网络预览选项卡中接收此数据,它看起来完全修改了我希望它接收的内容(它应该是一个 json 对象(,但它有所有这些添加的字符:

{&#34;temperature&#34;: 11.0, &#34;datetime&#34;: &#34;12-12-12 23-23-23&#34;}

我的谷歌图表的代码应该能够实时更新如下:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
  <div id="chart_div" style="width: 900px; height: 500px"></div>
   <script type="text/javascript">
    google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Date Time');
    data.addColumn('number', 'Temperature');
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    var options = {
      title: 'Temperature Data',
      curveType: 'none',
      legend: { position: 'bottom' }
    };
    drawChart();
    setInterval(drawChart, 10000);
    function drawChart() {
      $.getJSON({
        url: 'removed from public view just in case',
        type: 'get'
      }).done(function (jsonData) {
        data.addRows([
          [jsonData.datetime, jsonData.temperature]
        ]);
        chart.draw(data, options);
      }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
      });
    }
  },
  packages: ['corechart']
});
    </script>
    </body>
</html>

试试这个:

function decodeEntities(encodedString) {
  var textArea = document.createElement('textarea');
  textArea.innerHTML = encodedString;
  return textArea.value;
}
function drawChart() {
  $.getJSON({
    url: 'removed from public view just in case',
    type: 'get'
  }).done(function (jsonData) {
    jsonData = decodeEntities(jsonData);
    data.addRows([
      [jsonData.datetime, jsonData.temperature]
    ]);
    chart.draw(data, options);
  }).fail(function (jqXHR, textStatus, errorThrown) {
    console.log(textStatus, errorThrown);
  });
}

最新更新