表没有列。 Json数据

时间:2016-03-03 09:14:18

标签: javascript json google-visualization

我有这种格式的json数据

[
{
id: 2,
nom: "Dell",
type: "Pc",
quantity: 78,
prix: 7800
},
{
id: 3,
nom: "Intel",
type: "Processor",
quantity: 45,
prix: 8000
},
{
id: 4,
nom: "Dell",
type: "Ecran",
quantity: 10,
prix: 2500
}
] 

我希望将它们放在图表中帮助请大约4天我无法使其工作我想了解为什么谷歌图表api不想接受这些数据这是我的代码

<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript"  src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">

// Load the Visualization API and the bar package.
google.charts.load('current', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var jsonData = $.ajax({
      url: "http://localhost:8080/get",
      dataType: "json",
      async: false
      }).responseText;
      console.log(jsonData)
  // Create our data table out of JSON data loaded from server.


  var data = new google.visualization.DataTable(jsonData);

  // Instantiate and draw our chart, passing in some options.
  var chart = new    google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240});
}

</script>
</head>

<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

数据格式必须如下:

{
    cols: [
        {id: 'task', label: 'Task', type: 'string'},
        {id: 'hours', label: 'Hours per Day', type: 'number'}
    ],
    rows: [
        {c:[{v: 'Work'}, {v: 11}]},
        {c:[{v: 'Eat'}, {v: 2}]},
        {c:[{v: 'Commute'}, {v: 2}]},
        {c:[{v: 'Watch TV'}, {v:2}]},
        {c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}
    ]
}

查看文档(https://developers.google.com/chart/interactive/docs/reference#DataTable),您将看到必须在cols属性中定义列,并在rows属性中定义数据。

因此,您必须“重新格式化”您的JSON以符合要求。

因此,对于转换的需要,此代码应该有效:

var rows = new Array();

for(var i=0;i<jsonData.length;i++)
{
    var jsonRow = jsonData[i];
    var row = {
        c: [
            {v: jsonRow.id},
            {v: jsonRow.nom},
            {v: jsonRow.type},
            {v: jsonRow.quantity},
            {v: jsonRow.prix},
        ]
    };
    rows.push(row);
}


var dataFormatted = {
    cols: [
        { id: 'id', label: 'Id' },
        { id: 'nom', label: 'Nom' },
        { id: 'type', label: 'Type' },
        { id: 'quantity', label: 'Quantity' },
        { id: 'prix', label: 'Prix' },
    ],
    rows: rows
}

var data = new google.visualization.DataTable(dataFormatted);