Skip to content
Advertisement

assign json object to javascript variable in CanvasJS

Im trying to assign a json object to a variable. Im not sure how to accomplish this.

This is my JSON array:

[{
    "Date": "2020-01-24 07:35:46",
    "sensorName": "sensor 1",
    "sensorValue": 213
}, {
    "Date": "2020-01-24 07:35:46",
    "sensorName": "sensor 1",
    "sensorValue": 433
}, {
    "Date": "2020-02-10 06:03:36",
    "sensorName": "sensor 1",
    "sensorValue": 321
}, {
    "Date": "2020-02-10 06:03:36",
    "sensorName": "sensor 1",
    "sensorValue": 43
}, {
    "Date": "2020-02-12 03:30:57",
    "sensorName": "sensor 1",
    "sensorValue": 4321
}]

I wish to assign the value of sensorValue to variable yValue. how do i do this? Eg: for “sensorValue”:433, yValue = 433

<script>
var sensor1 = <?php echo json_encode($json_sensor1, JSON_NUMERIC_CHECK); ?>;
     var sensor2 = <?php echo json_encode($json_sensor2, JSON_NUMERIC_CHECK); ?>;

     var yValue1 = sensor1.sensorValue;
     var yValue2 = sensor2.sensorValue;
     var xValue = sensor1.Date;
</script>

Advertisement

Answer

CanvasJS accepts dataPoints as an array of objetcs as [{x: xValue1, y: yValue1}, {x: xValue2, y: yValue2},…]. Parsing your JSON to this format before passing it to chart-options should work fine.

var jsonData = [{
    "Date": "2020-01-24 07:35:46",
    "sensorName": "sensor 1",
    "sensorValue": 213
}, {
    "Date": "2020-01-24 07:35:46",
    "sensorName": "sensor 1",
    "sensorValue": 433
}, {
    "Date": "2020-02-10 06:03:36",
    "sensorName": "sensor 1",
    "sensorValue": 321
}, {
    "Date": "2020-02-10 06:03:36",
    "sensorName": "sensor 1",
    "sensorValue": 43
}, {
    "Date": "2020-02-12 03:30:57",
    "sensorName": "sensor 1",
    "sensorValue": 4321
}];

var dps = [];
var chart = new CanvasJS.Chart("chartContainer", {
  title:{
    text: "Basic Column Chart"
  },
  data: [{				
    dataPoints: dps
  }]
});

for(var i = 0; i < jsonData.length; i++) {
	dps.push({ x: new Date(jsonData[i].Date), y: Number(jsonData[i].sensorValue)})
}

chart.render();
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 200px; width: 100%;"></div>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement