[Chartjs]-Parsing JSON data into Chart.js bar chart

4๐Ÿ‘

โœ…

I made this quickly to give you an example to help you out, you were in the right direction. I have the snippet using hardcoded data for example purposes, and then at the bottom I used the Ajax method.

Parsed the data as so, similar to what you were doing by using data.map().

let region = [];
let rev_value = [];

try {
  data.map((item) => {
    rev_value.push(item.REV_VALUE);
    region.push(item.REGION);
  });
} catch (error) {
  console.log(error);
}

Then to use the data I just simply used a spread operator for the array contents [...].

labels: [...region],
data: [...rev_value],

Example 1 using Canvas.js simple example with your data hardcoded.

var ctx = document.getElementById('myChart').getContext('2d');

let data = [{
  "REGION": "Poland",
  "REV_VALUE": "2263"
}, {
  "REGION": "United States",
  "REV_VALUE": "1961"
}, {
  "REGION": "Spain",
  "REV_VALUE": "555"
}, {
  "REGION": "United Kingdom",
  "REV_VALUE": "380"
}, {
  "REGION": "Germany",
  "REV_VALUE": "314"
}];

let region = [];
let rev_value = [];

try {
  data.map((item) => {
    rev_value.push(item.REV_VALUE);
    region.push(item.REGION);
  });

  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: [...region],
      datasets: [{
        label: 'Regions',
        data: [...rev_value],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  });

} catch (error) {
  console.log(error);
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

Example 2 using your template and an Ajax call, change the URL for the request.

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
    function grab() {
        /* Promise to make sure data loads */
        return new Promise((resolve, reject) => {
            $.ajax({
                url: "/data.json",
                method: "GET",
                dataType: 'JSON',
                success: function(data) {
                    resolve(data)
                },
                error: function(error) {
                    reject(error);
                }
            })
        })
    }

    $(document).ready(function() {
        grab().then((data) => {
            console.log('Recieved our data', data);
            let regions = [];
            let value = [];

            try {
                data.forEach((item) => {
                    regions.push(item.REGION)
                    value.push(item.REV_VALUE)
                });

                let chartdata = {
                    labels: [...regions],
                    datasets: [{
                        label: 'Region',
                        backgroundColor: 'rgba(200, 200, 200, 0.75)',
                        borderColor: 'rgba(200, 200, 200, 0.75)',
                        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                        hoverBorderColor: 'rgba(200, 200, 200, 1)',
                        data: [...value]
                    }]
                };

                let ctx = $("#myChart");

                let barGraph = new Chart(ctx, {
                    type: 'bar',
                    data: chartdata
                });

            } catch (error) {
                console.log('Error parsing JSON data', error)
            }

        }).catch((error) => {
            console.log(error);
        })
    });
</script>

-2๐Ÿ‘

You can try something like this :

    dataPoints: variable ? variable.map((v) => ({x: (v.region), y: v.value})) : []

Leave a comment