0👍
✅
There are two problems in your code.
- As others already commented, the data in your
input
element is not of validJSON
format labels
itself is a string since it is surrounded by double quotes
To make it work, you can perform the following steps.
- parse the value from the input string with
JSON.parse
and extractlabels
(that’s what you already did). - replace all single quotes by double quotes in the obtained
labels
string. - parse the labels string to a
JSON
array using againJSON.parse
.
const labelsAsString = JSON.parse(document.getElementById('ctl00_ctl00_cphMain_cphMacTool_DASHBOARD').value).labels;
const labelsAsJSONString = labelsAsString.replace(/'/g,'"');
const labelsArray = JSON.parse(labelsAsJSONString);
Please have a look at your amended code below and see how it works.
const labelsAsString = JSON.parse(document.getElementById('ctl00_ctl00_cphMain_cphMacTool_DASHBOARD').value).labels;
const labelsAsJSONString = labelsAsString.replace(/'/g,'"');
const labelsArray = JSON.parse(labelsAsJSONString);
new Chart('line-chart', {
type: 'line',
data: {
labels: labelsArray,
datasets: [{
data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200],
label: "Processed",
borderColor: "#9C2AA0",
fill: false
},
{
data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200],
label: "Error",
borderColor: "#123456",
fill: false
},
{
data: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200],
label: "Not Processed",
borderColor: "#A8B400",
fill: false
}
]
},
options: {
title: {
display: false,
text: '',
fontColor: '#000000',
fontFamily: 'Calibri',
fontSize: 30
},
legend: {
position: 'top',
labels: {
fontColor: '#000000',
fontFamily: 'Calibri',
boxWidth: 20,
fontSize: 20
}
},
scales: {
xAxes: [{
ticks: {
fontColor: '#000000'
}
}],
yAxes: [{
ticks: {
fontColor: '#000000'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<input id="ctl00_ctl00_cphMain_cphMacTool_DASHBOARD" value="{ "labels": "['jan', 'Feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']" }">
<canvas id="line-chart" height="80"></canvas>
0👍
The JSON I posted was valid but when parsed, returned a string. As uminder mentioned, labels needs to be an array hence replacing single quotes with double quotes and parsing twice returns an object. This worked! Really appreciate the help.
Source:stackexchange.com