将JSON数据解析为Chart.js条形图

时间:2019-03-21 22:42:58

标签: javascript json ajax chart.js

我正在尝试使用 Chart.js 来使用从Oracle DB动态生成的数据来生成条形图。我无法以正确的格式获取数据,我想我已经接近了,但是已经被卡住了一段时间了。

我的JSON文件:

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

这是我的barchar.js文件:

$(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>

我试图实现在其他主题中找到的解决方案,但仍然没有成功。 任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

我迅速做到了这一点,为您提供了一个可以帮助您的示例,您的方向正确。我有使用硬编码数据作为示例的代码段,然后在底部使用了Ajax方法。

如此解析数据,类似于使用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);
}

然后使用数据,我只是简单地对数组内容[...]使用了一个扩展运算符。

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

示例1使用Canvas.js简单示例,并对数据进行硬编码。

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>

  

示例2使用您的模板和Ajax调用,更改请求的URL。

<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>

答案 1 :(得分:-2)

您可以尝试这样的事情:

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