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

问题描述 投票:2回答:2

我正在尝试使用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>

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

javascript json ajax chart.js
2个回答
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/[email protected]/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/[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>

-2
投票

你可以尝试这样的事情:

    dataPoints: variable ? variable.map((v) => ({x: (v.region), y: v.value})) : []
© www.soinside.com 2019 - 2024. All rights reserved.