如何将json文件转换为图形? [英] How to turn a json files into a graph?

查看:155
本文介绍了如何将json文件转换为图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取json编码的页面,从中获取价值,并将其转化为页面上的图形.

I am trying to read json encoded page, get value from it and make it into graph on a page.

这是json文档的样子:

This is how the json document looks like:

[{"time":"1561430809","ip":"192.168.102.166","waterlevel":null,"station":null,"humidity":null,"temperature":null},{"time":"1561390045","ip":"192.168.103.151","waterlevel":"419","station":"Near the Training Center","humidity":"0","temperature":"0"}]

这是页面代码:

<!doctype html>
<html>
 
<head>
  <title>Line Chart | Abaarso school</title>
  <!--For offline ESP graphs see this tutorial https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/ -->
  <script src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>  
  <style>
  canvas{
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
  }
 
  /* Data Table Styling */
  #dataTable {
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 100%;
  }
 
  #dataTable td, #dataTable th {
    border: 1px solid #ddd;
    padding: 8px;
  }
 
  #dataTable tr:nth-child(even){background-color: #f2f2f2;}
 
  #dataTable tr:hover {background-color: #ddd;}
 
  #dataTable th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: #4CAF50;
    color: white;
  }
  </style>
</head>
 
<body>
    <div style="text-align:center;"><b>test</b><br></br>Real Time Data: Humidity, Temperature Logging with Graphs</div>
    <div class="chart-container" position: relative; height:350px; width:100%">
        <canvas id="Chart" width="400" height="400"></canvas>
    </div>
<div>
  <table id="dataTable">
    <tr><th>Time</th><th>Water level (ml)</th><th>Temperaure (&deg;C)</th><th>Humidity (%)</th></tr>
  </table>
</div>
<br>
<br>  
 
<script>
//Graphs visit: https://www.chartjs.org
var ADCvalues = [];
var Tvalues = [];
var Hvalues = [];
var timeStamp = [];
function showGraph()
{
    var ctx = document.getElementById("Chart").getContext('2d');
    var Chart2 = new Chart(ctx, {
        type: 'line',
        data: {
            labels: timeStamp,  //Bottom Labeling
            datasets: [{
                label: "water level",
                fill: false,  //Try with true
                backgroundColor: 'rgba( 243,18, 156 , 1)', //Dot marker color
                borderColor: 'rgba( 243, 18, 156 , 1)', //Graph Line Color
                data: ADCvalues,
            },{
                label: "Temperature",
                fill: false,  //Try with true
                backgroundColor: 'rgba( 243, 156, 18 , 1)', //Dot marker color
                borderColor: 'rgba( 243, 156, 18 , 1)', //Graph Line Color
                data: Tvalues,
            },
            {
                label: "Humidity",
                fill: false,  //Try with true
                backgroundColor: 'rgba(156, 18, 243 , 1)', //Dot marker color
                borderColor: 'rgba(156, 18, 243 , 1)', //Graph Line Color
                data: Hvalues,
            }],
        },
        options: {
            title: {
                    display: true,
                    text: "Station A: near the training center"
                },
            maintainAspectRatio: false,
            elements: {
            line: {
                    tension: 0.5 //Smoothening (Curved) of data lines
                }
            },
            scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        }
                    }]
            }
        }
    });
 
}
 
//On Page load show graphs
window.onload = function() {
  console.log(new Date().toLocaleTimeString());
};
 
//Ajax script to get ADC voltage at every 5 Seconds 
//Read This tutorial https://circuits4you.com/2018/02/04/esp8266-ajax-update-part-of-web-page-without-refreshing/
 
setInterval(function() {
  // Call a function repetatively with 5 Second interval
  getData();
}, 5000); //5000mSeconds update rate
 
function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     //Push the data in array
  var time = new Date().toLocaleTimeString();
  var txt = this.responseText;
  var obj = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
      ADCvalues.push(obj.waterlevel);
      Tvalues.push(obj.temperature);
      Hvalues.push(obj.humidity);
      timeStamp.push(time);
      showGraph();  //Update Graphs
  //Update Data Table
    var table = document.getElementById("dataTable");
    var row = table.insertRow(1); //Add after headings
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    cell1.innerHTML = time;
    cell2.innerHTML = obj.waterlevel;
    cell3.innerHTML = obj.temperature;
    cell4.innerHTML = obj.humidity;
    }
  };
  xhttp.open("GET", "http://abdikani.local.ask.org/json.php", true); //Handle readADC server on ESP8266
  xhttp.send();
}
    
</script>
</body>
 
</html>
 

我没有从本地json页面获取值,因此无法绘制图形.我这是怎么了?我只需要从json编码的页面中获取值,然后在折线图上显示它们即可.

I don't get the values from my local json page and thus can't graph it. What am I getting wrong here? I just need to get the values from the json encoded page and then show them on a line graph.

这是错误.

Uncaught TypeError: Cannot read property 'skip' of undefined
    at l (Chart.min.js:10)
    at u (Chart.min.js:10)
    at a (Chart.min.js:10)
    at t.getElementsAtEventForMode (Chart.min.js:10)
    at t.handleEvent (Chart.min.js:10)
    at t.eventHandler (Chart.min.js:10)
    at n (Chart.min.js:10)
    at HTMLCanvasElement.x.<computed> (Chart.min.js:10)
133Chart.min.js:10 Uncaught TypeError: Cannot read property 'skip' of undefined
    at l (Chart.min.js:10)
    at u (Chart.min.js:10)
    at a (Chart.min.js:10)
    at t.getElementsAtEventForMode (Chart.min.js:10)
    at t.handleEvent (Chart.min.js:10)
    at t.eventHandler (Chart.min.js:10)
    at n (Chart.min.js:10)
    at HTMLCanvasElement.x.<computed> (Chart.min.js:10)

Json.php中的代码是:

The code in the Json.php is:

<?php
$dab=new PDO('sqlite:waterlevel');
$st=$dab->prepare('select time, ip, waterlevel, station, humidity, temperature from waterlevel group by station order by time desc limit 100');
$st->execute();
$sv=$st->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($sv);
?>

推荐答案

出现此错误是因为您试图访问对象值数组,您拥有多个对象,而不仅仅是一个对象,因此您可能希望对其进行迭代.一种迭代方法是使用forEach()(在此处阅读).

The error appears because you are trying to accessing array of object values, you have a multiple object, not just one, so you might want to iterate them. One of the solution to iterate throught it are by using forEach() (read here).

您可能还必须更改数据库列以使其不能为空.

You also might have to chage your database columns to be not nullable.

<!DOCTYPE html>
<html>
    <head>
        <title>Line Chart | Abaarso school</title>
        <!--For offline ESP graphs see this tutorial https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/ -->
        <script src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
        <meta charset="UTF-8">
        <style>
        canvas{
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
        }

        /* Data Table Styling */
        #dataTable {
            font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }

        #dataTable td, #dataTable th {
            border: 1px solid #ddd;
            padding: 8px;
        }

        #dataTable tr:nth-child(even){background-color: #f2f2f2;}

        #dataTable tr:hover {background-color: #ddd;}

        #dataTable th {
            padding-top: 12px;
            padding-bottom: 12px;
            text-align: left;
            background-color: #4CAF50;
            color: white;
        }
        </style>
    </head>
    <body>
        <div style="text-align:center;"><b>test</b><br></br>Real Time Data: Humidity, Temperature Logging with Graphs</div>
        <div class="chart-container" position: relative; height:350px; width:100%">
            <canvas id="Chart" width="400" height="400"></canvas>
        </div>
        <div>
            <table id="dataTable">
                <tr><th>Time</th><th>Water level (ml)</th><th>Temperaure (&deg;C)</th><th>Humidity (%)</th></tr>
            </table>
        </div>
        <br>
        <br>  

        <script>
        //Graphs visit: https://www.chartjs.org
        var ADCvalues = [];
        var Tvalues = [];
        var Hvalues = [];
        var timeStamp = [];
        function showGraph()
        {
            var ctx = document.getElementById("Chart").getContext('2d');
            var Chart2 = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: timeStamp,  //Bottom Labeling
                    datasets: [{
                        label: "water level",
                        fill: false,  //Try with true
                        backgroundColor: 'rgba( 243,18, 156 , 1)', //Dot marker color
                        borderColor: 'rgba( 243, 18, 156 , 1)', //Graph Line Color
                        data: ADCvalues,
                    },{
                        label: "Temperature",
                        fill: false,  //Try with true
                        backgroundColor: 'rgba( 243, 156, 18 , 1)', //Dot marker color
                        borderColor: 'rgba( 243, 156, 18 , 1)', //Graph Line Color
                        data: Tvalues,
                    },
                    {
                        label: "Humidity",
                        fill: false,  //Try with true
                        backgroundColor: 'rgba(156, 18, 243 , 1)', //Dot marker color
                        borderColor: 'rgba(156, 18, 243 , 1)', //Graph Line Color
                        data: Hvalues,
                    }],
                },
                options: {
                    title: {
                            display: true,
                            text: "Station A: near the training center"
                        },
                    maintainAspectRatio: false,
                    elements: {
                    line: {
                            tension: 0.5 //Smoothening (Curved) of data lines
                        }
                    },
                    scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero:true
                                }
                            }]
                    }
                }
            });

        }

        //On Page load show graphs
        window.onload = function() {
          console.log(new Date().toLocaleTimeString());
        };

        //Ajax script to get ADC voltage at every 5 Seconds 
        //Read This tutorial https://circuits4you.com/2018/02/04/esp8266-ajax-update-part-of-web-page-without-refreshing/

        setInterval(function() {
          // Call a function repetatively with 5 Second interval
          getData();
        }, 5000); //5000mSeconds update rate

        function getData() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    //Push the data in array
                    var time = new Date().toLocaleTimeString();
                    var txt = this.responseText;
                    var obj = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
                    console.log(obj);
                    obj.forEach(function(element_data){
                        console.log(element_data);
                        ADCvalues.push(element_data.waterlevel);
                        Tvalues.push(element_data.temperature);
                        Hvalues.push(element_data.humidity);
                        timeStamp.push(time);
                        showGraph();
                        var table = document.getElementById("dataTable");
                        var row = table.insertRow(1); //Add after headings
                        var cell1 = row.insertCell(0);
                        var cell2 = row.insertCell(1);
                        var cell3 = row.insertCell(2);
                        var cell4 = row.insertCell(3);
                        cell1.innerHTML = time;
                        cell2.innerHTML = element_data.waterlevel;
                        cell3.innerHTML = element_data.temperature;
                        cell4.innerHTML = element_data.humidity;
                    });
                }
            };
            xhttp.open("GET", "http://abdikani.local.ask.org/json.php", true); // Works fine with me using the same json document locally - Handle readADC server on ESP8266
            xhttp.send();
        }
        </script>
    </body>
</html>

这篇关于如何将json文件转换为图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆