Chartjs-Reference Javascript variable in JSON

0👍

There are two problems in your code.

  1. As others already commented, the data in your input element is not of valid JSON format
  2. labels itself is a string since it is surrounded by double quotes

To make it work, you can perform the following steps.

  1. parse the value from the input string with JSON.parse and extract labels (that’s what you already did).
  2. replace all single quotes by double quotes in the obtained labels string.
  3. parse the labels string to a JSON array using again JSON.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="{ &quot;labels&quot;: &quot;['jan', 'Feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']&quot; }">
<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.

Leave a comment