当前位置: 首页 > 知识库问答 >
问题:

Google Chart API折线图上的JSON字符串无效

许展鹏
2023-03-14

我正在尝试使用Google Charts API创建一个基于MySQL数据库的折线图。数据库包含温度和时间戳。

我使用getData.php获取数据并将其转换为JSON。

<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";


$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$qry = "SELECT * FROM temp";

$result = mysqli_query($conn,$qry);

$table = array();
$table['cols'] = array(

    array('label' => 'Time', 'type' => 'datetime'),
    array('label' => 'Temperature', 'type' => 'number')
);

$rows = array();
foreach($result as $row){

    $temp = array();

    //$temp[] = array('v' => 'Date(' . $row['time'] . ')'); OLD

    //turn timestamps into correct datetime form Date(Y,n,d,H,i,s) 
    $temp[] = array('v' => 'Date('.date('Y',strtotime($row['time'])).',' . 
                                 (date('n',strtotime($row['time'])) - 1).','.
                                 date('d',strtotime($row['time'])).','.
                                 date('H',strtotime($row['time'])).','.
                                 date('i',strtotime($row['time'])).','.
                                 date('s',strtotime($row['time'])).')'); 


    $temp[] = array('v' => (float) $row['temperature']); 
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;

$jsonTable = json_encode($table, true);
echo $jsonTable;    
?>

按照Google在此的说明:https://developers.google.com/chart/interactive/docs/datesandtimes#dates-times-and-timezones将时间戳转换为“日期(年、月、日、小时、分钟、秒、毫秒)”格式

这是我的main.html。它基于Google的示例(https://developers.google.com/chart/interactive/docs/phpexample#exampleusingphphtml-file)

<html>
<head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">

      // Load the Visualization API and the corechart package.
        google.charts.load('current', {'packages':['line']});

      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var jsonData = $.ajax({
          url: "getData.php",
          dataType: "json",
          async: false
          }).responseText;

        var data = new google.visualization.DataTable(jsonData); //Line 27


        var options = {'title':'Temperature',
                       'width':720,
                       'height':480};

        var chart = new google.charts.Line(document.getElementById('chart_div'));


        //chart.draw(data, options);
        //chart.draw(data, {width: 400, height: 240});
        chart.draw(data, google.charts.Line.convertOptions(options));



      }
    </script>

</head>

<body>
   <div id="chart_div"><p id="test"></p></div>
</body>
<html>

网站为空白,Chrome调试器显示此错误:

未捕获得错误:无效得JSON字符串:

<body>
{"cols":[{"label":"Time","type":"datetime"},{"label":"Temperature","type":"number"}],"rows":[{"c":[{"v":"Date(2016,3,14,10,36,30)"},{"v":22}]},{"c":[{"v":"Date(2016,3,14,10,37,31)"},{"v":25}]},{"c":[{"v":"Date(2016,3,14,10,37,53)"},{"v":21}]},{"c":[{"v":"Date(2016,3,15,01,23,37)"},{"v":21}]}]}
</body>

yl @ VM1981:170
Ol @ VM1981:174
Sp @ VM1981:234
drawChart @ main.html:27
google.a.b.Na @ loader.js:147
g @ loader.js:145

main.html:27是var data=new google.visualization.dataTable(jsonData);行。

下面是用jsonlint格式化的JSON

{
"cols": [{
    "label": "Time",
    "type": "datetime"
}, {
    "label": "Temperature",
    "type": "number"
}],
"rows": [{
    "c": [{
        "v": "Date(2016,3,14,10,36,30)"
    }, {
        "v": 22
    }]
}, {
    "c": [{
        "v": "Date(2016,3,14,10,37,31)"
    }, {
        "v": 25
    }]
}, {
    "c": [{
        "v": "Date(2016,3,14,10,37,53)"
    }, {
        "v": 21
    }]
}, {
    "c": [{
        "v": "Date(2016,3,15,01,23,37)"
    }, {
        "v": 21
    }]
}]
}

我在这里完全不知所措。JSON字符串应该很好,并且也通过jsonlint.com进行了验证。如有任何帮助,将不胜感激。

共有1个答案

宰父子安
2023-03-14

在getData.php中复制代码并返回粘贴的json字符串,我无法再现错误。

请检查main.html中的ajax响应:

console.log(jsonData);

如果我在getdata.php中添加额外的输出(例如var_dump一些东西),我可以创建无效的JSON字符串错误。这个

<body>

但是JSON字符串周围的标记是可疑的,因为在错误消息中打印的是格式错误的JSON字符串,因此标记似乎是JSON-String的一部分。getData.php中的php代码是否嵌入到正文标记中?

在main.html中,您可以尝试:

jsonData=jsonData.replace("<body>", "").replace("</body>", "");

检查一下,如果这可能是问题所在。

 类似资料:
  • 在Jenkins中解析json文件时面临以下错误 Json文件 错误 hudson.remoting.代理异常:net.sf.json.JSONExcture:无效的JSON字符串在net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:143)在net.sf.json.JSONSerializer.toJSON(JSONSerializer.j

  • 问题内容: 我有一个无效的json字符串,如下所示, 我尝试使用JSON.parse将其转换为对象。但是,这不是有效的json字符串。是否有任何函数可以将这种无效格式转换为有效的json字符串或直接转换为对象? 问题答案: 如果您的示例语法与真实JSON相同,则JSONLint表示您需要对名称和值使用双引号。 仅在这种情况下,请使用以下替换调用: 但是,您首先应该尝试使用有效的Json。

  • 基本折线图 <template> <ve-line :data="chartData" :settings="chartSettings"></ve-line> </template> <script> export default { data () { this.chartSettings = {} return { chartData: { columns: ['日期',

  • 实时显示传感器数据。 用法 Your browser does not support the video tag. 案例:数据变化趋势 功能:显示数字改变的规律

  • 我有以下JSON字符串: 我只想要和。我试过这样的方法: 但我得到了以下错误: 我只使用过几次JSON。有人能帮我吗? 对我来说最好的例子是这样的,我在另一个例子中做过: 可能吗? 现在我已经做到了: 我试着这样做: 然后: 但现在当我做一个Prtinout时,我会得到和以前一样的错误:

  • 问题内容: 而不是从json字符串中使用$ .parseJSON,我需要获取对象并将其存储在变量中作为代表json的字符串。 (我正在处理的库期望使用格式错误的json类型,因此我需要弄乱它才能使其正常工作。) 最好的方法是什么? 问题答案: 编辑: 您应该使用Douglas Crockford的json2.js库,而不是实现下面的代码。它提供了一些额外的功能以及更好/更旧的浏览器支持。 从以下位