Jack84
Jack84

Reputation: 79

Parsing JSON data into Chart.js bar chart

I'm trying to use Chart.js to generate a bar chart using dynamically generated data from Oracle DB. I'm having trouble getting the data in the right format, I think I'm close but I've been stuck for a while.

My JSON file:

[{"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"}]

And here is my barchar.js file:

$(document).ready(function(){
  $.ajax({
    url: "http://localhost/DWH/dataJSON.php",
    method: "GET",
    dataType : 'JSON',
    success: function(data) {
      console.log(data);
      var region = [];
      var value = [];

      for(var i in data) {
        region.push(data[i].REGION);
        value.push(data[i].REV_VALUE);
      }

      var chartdata = {
        labels: region,
        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.map(function(x) {return x * 1;})
          }
        ]
      };

      var ctx = $("#myChart");

      var barGraph = new Chart(ctx, {
        type: 'bar',
        data: chartdata
      });
    },
    error: function(data) {
      console.log(data);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>

I tried to implement a solution that I found in other topics, but still without success. Any help would be very much appreciated!

Upvotes: 4

Views: 14055

Answers (2)

ABC
ABC

Reputation: 2128

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/[email protected]/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/[email protected]/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>

Upvotes: 5

Ilias Korompilis
Ilias Korompilis

Reputation: 1

You can try something like this :

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

Upvotes: -2

Related Questions