[Chartjs]-How to integrate mustache template to read json data and dynamically display it in Chartjs

0👍

You can use the structure of the data.json as dataset.data. But to enable CHART.JS to read correctly the data, you should set options.parsing option at chart level, as following:

options: {   
  parsing: {
    xAxisKey: 'name',
    yAxisKey: 'value'
  }    
}

See documentation of CHART.JS: https://www.chartjs.org/docs/latest/general/data-structures.html#object-using-custom-properties

const barGraph = [
  {
    "name": "A",
    "value": 4
  },
  {
    "name": "AAA",
    "value": 10
  },
  {
    "name": "B",
    "value": 40
  },
  {
    "name": "BB",
    "value": 20
  },
  {
    "name": "BBB",
    "value": 7
  }
];     

const barCtx = document.getElementById('myChart').getContext('2d');
     new Chart(barCtx, barGraphConfig());
     function barGraphConfig() {
      return {
      type: 'bar',
      data: {
        datasets: [
        {
          data: barGraph,
          borderRadius: 5,
          backgroundColor: [
            '#fece8c',
            '#a28cfe',
            '#a28cfe',
            '#feab8c',
            '#8ca2fe',
            '#8ca2fe',
          ],
          barThickness: 20
        }
      ],
    },
    options: {   
      parsing: {
        xAxisKey: 'name',
        yAxisKey: 'value'
      }    
    }
  };
}
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

Leave a comment