简体   繁体   English

使用JSON的Google Charts

[英]Google Charts using JSON

I have not used Google Charts before, but I am trying to do some temperature graphing using sensors located around the house, however I keep getting an Exception. 我以前没有使用谷歌图表,但我正在尝试使用位于房子周围的传感器进行一些温度图表,但是我不断得到一个例外。 I'm fairly certain its because the JSON is not in the correct format but struggling on what format it needs and how to get my script to generate JSON in that format. 我很确定它是因为JSON的格式不正确,但是在它需要什么格式以及如何让我的脚本以这种格式生成JSON方面苦苦挣扎。

PHP script generating JSON from database PHP脚本从数据库生成JSON

<?php
require_once ("config.php");

$array = array();
$res = mysqli_query($con, "SELECT * FROM sensors WHERE vera_variable='CurrentTemperature'");
while ($row = mysqli_fetch_array($res)) {
    $sensor_id = $row['sensor_id'];
    $sensor_name = $row['sensor_name'];

    $res2 = mysqli_query($con, "SELECT * FROM logs WHERE sensor_id='$sensor_id'");
    while ($row2 = mysqli_fetch_array($res2)) {
        $time = strtotime($row2['log_time']);
        $formattedTime = date("m-d-y g:i", $time);

        $sensor_value = $row2['sensor_value'];

            $array[$formattedTime][$sensor_name] = $sensor_value;
    }
}

$json = json_encode($array,  JSON_PRETTY_PRINT);
echo "<pre>" . $json . "</pre>";

?>

An example output from the above script. 上述脚本的示例输出。 You can see there is a date, multiple sensors and their coresponding values 您可以看到有一个日期,多个传感器及其相应的值

{
    "12-12-15 8:35": {
        "Living Room Temperature": "18.3",
        "Outside Temperature": "-5",
        "Mud Room Temperature": "16.0",
        "Basement Temperature": "14.0"
    },
    "12-12-15 8:40": {
        "Living Room Temperature": "18.3",
        "Outside Temperature": "-5",
        "Mud Room Temperature": "16.0",
        "Basement Temperature": "13.0"
    },
    "12-12-15 8:45": {
        "Living Room Temperature": "18.3",
        "Outside Temperature": "-5",
        "Mud Room Temperature": "16.0",
        "Basement Temperature": "13.0"
    },
    "12-12-15 8:50": {
        "Living Room Temperature": "18.3",
        "Outside Temperature": "-5",
        "Mud Room Temperature": "16.0",
        "Basement Temperature": "13.0"
    },
    "12-12-15 8:55": {
        "Living Room Temperature": "18.3",
        "Outside Temperature": "-5",
        "Mud Room Temperature": "16.0",
        "Basement Temperature": "13.0"
    },
    "12-12-15 9:00": {
        "Living Room Temperature": "17.8",
        "Outside Temperature": "-5",
        "Mud Room Temperature": "16.0",
        "Basement Temperature": "13.0"
    }
    }

The following is what I have (just a simple example chart using json) 以下是我所拥有的(只是一个使用json的简单示例图表)

<html>
    <head>
        <!-- Load jQuery -->
        <script language="javascript" type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
        <!-- Load Google JSAPI -->
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("visualization", "1", {
                packages : ["corechart"]
            });
            google.setOnLoadCallback(drawChart);

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

                var obj = window.JSON.stringify(jsonData);
                var data = google.visualization.arrayToDataTable(obj);

                var options = {
                    title : 'Graph'
                };

                var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
                chart.draw(data, options);
            }

        </script>
    </head>
    <body>
        <div id="chart_div" style="width: 900px; height: 500px;"></div>
    </body>
</html>

EDIT: Here is the error that Chrome shows when trying to load the graph: 编辑:以下是Chrome在尝试加载图表时显示的错误:

Uncaught Error: Not an arraylha @ format+en,default+en,ui+en,corechart+en.I.js:191bha @ format+en,default+en,ui+en,corechart+en.I.js:193drawChart @ temperature.php:22 未捕获错误:不是arraylha @ format + en,默认+ en,ui + en,corechart + en.I.js:191bha @ format + en,默认+ en,ui + en,corechart + en.I.js:193drawChart @ temperature.php:22

This error occurs since the input JSON data format ( obj variable) is not compatible with Google Chart data JSON format. 由于输入JSON数据格式( obj变量)与Google Chart数据JSON格式不兼容 ,因此会发生此错误。

You could transform the input data to the supported format as demonstrated below: 您可以将输入数据转换为支持的格式,如下所示:

var chartData = [];
chartData.push(['Time','Living Room Temperature','Outside Temperature','Mud Room Temperature','Basement Temperature']);
for (var key in obj) {
     var item = obj[key];
     chartData.push([new Date(key),parseFloat(item['Living Room Temperature']),parseFloat(item['Outside Temperature']),parseFloat(item['Mud Room Temperature']),parseFloat(item['Basement Temperature'])]);       
 }
 var data = google.visualization.arrayToDataTable(chartData);

Working example 工作实例

Some changes have been made on how data is loaded, in particular since it's considered a bad practice to perform synchronous calls async is set to true . 对数据的加载方式进行了一些更改,特别是因为将同步调用async设置为true被认为是一种不好的做法。 In addition, requests are handled via promises . 此外,请求通过promises处理。

 google.load("visualization", "1", { packages: ["corechart"] }); google.setOnLoadCallback(drawChart); function drawChart() { $.ajax({ url: "https://gist.githubusercontent.com/vgrem/e08a3da68a5db5e934a1/raw/2f971a9d1524d0457a6aae4df861dc5f0af0a2ef/data.json", //json_temp.php dataType: "json" }) .done(function (data) { var chartData = []; chartData.push(['Time','Living Room Temperature','Outside Temperature','Mud Room Temperature','Basement Temperature']); for (var key in data) { var item = data[key]; chartData.push([new Date(key),parseFloat(item['Living Room Temperature']),parseFloat(item['Outside Temperature']),parseFloat(item['Mud Room Temperature']),parseFloat(item['Basement Temperature'])]); } var dataTable = google.visualization.arrayToDataTable(chartData); var options = { title: 'Graph' }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(dataTable, options); }); } 
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <div id="chart_div" style="width: 900px; height: 500px;"></div> 

Looks like you are passing an Object instead of the expected Array . 看起来你正在传递一个Object而不是预期的Array

Try this instead: 试试这个:

var obj = window.JSON.stringify(jsonData);
var arr = [];
Object.keys(obj).forEach(function(key){
   var o = obj[key]; 
   o.time = key; 
   arr.push(o);
});
var data = google.visualization.arrayToDataTable(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM