Utilizing JSON for Google Charts

Although I have no prior experience with Google Charts, I am currently attempting to graph temperature data collected from sensors placed around my house. Unfortunately, I keep encountering an Exception error. I suspect the issue lies in the JSON format not being correct, but I'm struggling to determine the necessary format and how to modify my script to generate JSON accordingly.

The PHP script provided below is responsible for generating JSON data from the database:

<?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 of the script includes a date, multiple sensors, and their corresponding values.

{
    "12-12-15 8:35": {
        "Living Room Temperature": "18.3",
        "Outside Temperature": "-5",
        "Mud Room Temperature": "16.0",
        "Basement Temperature": "14.0"
    },
    // additional data entries...
}

Beyond this point is a simple example chart using JSON:

<html>
    <head>
        <script language="javascript" type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>

        <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>

Upon trying to load the graph, Chrome displays the following error message:

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

Answer №1

This issue arises because the input JSON data format (obj variable) does not align with the required Google Chart data JSON format.

To resolve this, you can convert the input data to the corrected format by following the example 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);

Example in action

Modifications have been implemented on how the data is retrieved, as synchronous calls are discouraged and replaced with async: true. Moreover, requests now utilize 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>

Answer №2

It appears that you're passing an Object instead of the expected Array.

Here's an alternative approach:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating complex JSON structure for incoming data object

Here is a sample class structure to consider: public class Foo { private String x; private String y; private String z; private Bar w; } From this structure, I aim to produce the JSON representation shown below: { "values": { ...

Having difficulty resolving JSON Object code

I am struggling to write an Android code to retrieve a JSON array. Despite following numerous tutorials, I have been unable to find a solution. Can anyone help me solve this issue? Below is the JSON data: { "total_records":"3370", "count":100, ...

Is it permissible to define a serialized key under the identifier "constant" in Java programming language?

I have been trying to create a POJO that I can convert to JSON using GSON. The JSON format I am aiming for is as follows: { "static":"value", "otherkey": "value" } Based on this structure, my POJO currently looks like this: public class MyPOJO { pu ...

Whenever I attempt to retrieve JSON data, I keep receiving an [object object] alert

When I try to retrieve JSON data from an online server instead of localhost, I'm encountering an [object object] alert. The code works perfectly on localhost. Here is the ASPX code: $(document).ready(function () { $('#btnGetEmployee&a ...

Short-circuiting async flows on non-error events in Node.js

Node implements the CPS convention for callbacks. Typically, when a function encounters an error, it is common practice to either handle the error or callback the error to the parent function by utilizing something like return cb(err). One challenge I fac ...

Issues with Loading Bootstrap JavaScript on Basic "Hello World" Project

I am experiencing an issue where the JavaScript code is not displaying on my website. I have checked the inspect element sources and it seems to load correctly, but for some reason, it is not being applied. Any insights on why this might be happening? Than ...

Images on web pages are automatically resized to fit into a smaller preview window

Currently, I am facing an issue with the display of images in my grid windows on my website . The images are appearing as partial representations instead of rescaled versions where the whole picture is resized to fit the grid window. I have attempted mod ...

The JScrollPane fails to appear during the initial page load

After successfully logging in on my website's login page, I navigate to the second page and encounter an issue where the ScrollBar doesn't show up on first load. I have to refresh the page once more for it to appear. Has anyone else experienced t ...

Struggling with adding two-digit numbers in a JavaScript calculator

While I can add single digits with no problem, adding double digits proves to be a bit tricky. The split method in this if statement is useful for isolating individual numbers, but it struggles when dealing with double digit numbers. if(e.value == '= ...

Challenges with JArrays

Having issues with JSON Parse and Jarray.Length. The goal of this app is to: metin variable serves as the search string. For example, if I input "DDDDDD", the SOFTWARE will search in the JSON file for "DDDDD" and display DDDDD's features on the consol ...

"Using PHP to generate HTML code for creating a hyperlink with

I am looking to pass ID values using GET to another website. These IDs are retrieved from a database and stored in the $row variable. <table> <?php foreach ($pdo->query($sql) as $row) { ?> <tr> <td><?php echo $row[ ...

Parameters keyword within a JSON object

When I am constructing a JSON object in my code, I come across an issue with the property params. This prevents me from creating the object as intended. Here is the snippet of my code: using Newtonsoft.Json.Linq; JObject json = JObject.FromObject(new { ...

JavaScript code encounters difficulties parsing HTML source

I'm attempting to reconstruct the WhateverOrigin service, which can be found at this link: Nevertheless, when I try running it in my web browser, this code that functioned perfectly with WhateverOrigin no longer functions properly with my imitation s ...

Conditional Matching with Javascript Regular Expressions

My strings are formatted like this: #WTK-56491650H #=> want to capture '56491650H' #M123456 #=> want to capture 'M123456' I am trying to extract everything after the # character, unless there is a dash. In that case, I onl ...

Merge all JSON files after indexing them using jq into a single JSON file

I have multiple json files stored in a directory, such as: file1.json [ { "name": "Alice" }, { "name": "Bob" } ] file2.json [ { "name": "Eve" }, { "name": "Charlie ...

Having trouble loading a JSON object into a Datatable using Jquery?

I am currently utilizing DataTables in combination with Jquery. I have a data source in the form of an JSON object that I intend to retrieve via Ajax and showcase within the table. The JSON data is retrieved from the /live/log url and has the following fo ...

What is the most effective method for identifying the initial timestamp for each day, week, or month within a collection of timestamps?

I am dealing with a lengthy array of sorted timestamps representing stock price quotes. These timestamps have minimal resolution, meaning that each timestamp is at least 1 minute bigger than the previous one. However, there can be gaps during the day, espe ...

Running function without the need to click on 'li' element

In the process of developing a simple guessing game, my aim is to allow users to click on a number and have that number stored as userAnswer, while the computerAnswer is a randomly generated number between one and ten. Despite setting the setVariables() f ...

Encountering a "403 Forbidden" error upon deployment to the server due to

Situation: I am developing a website using Spring web MVC, JSP, and HTML/JavaScript. One of the features I have implemented is a search function that communicates with imdbapi.org to retrieve movie/TV show information in JSON format via AJAX. The JSON resp ...

error: cannot parse data with Jquery, AJAx, and JSON

Can you assist me with this issue: I am currently building a search page using PHP and attempting to fetch a specific record from a MySQL table through JQuery-AJAX-JSON. However, the problem I'm facing is that I do not receive any data from process.p ...