如何通过JSON对象为ColumnChart创建DataTable?

时间:2013-03-12 15:43:21

标签: json visualization

我正在尝试使用JSON作为参数创建一个DataTable,用于来自Google可视化API的ColumnChart。

我生成了以下JSON对象:

{
    "cols": [
        {"id":"date", "label":"date","pattern":"", "type":"date"},
        {"id":"jobsonstatus", "label":"jobsonstatus", "pattern":"", "type":"number"}
    ],
    "rows": [
        {
            "c": [
                {"v": "01-02-2013", "f": null},
                {"v": 128, "f": null}
            ]
        },
        {
            "c": [
                {"v": "08-02-2013", "f": null},
                {"v": 185, "f": null}
            ]
        },
        {
            "c": [
                {"v": "15-02-2013", "f": null},
                {"v": 142, "f": null}
            ]
        },
        {
            "c": [
                {"v": "22-02-2013", "f": null},
                {"v": 86, "f": null}
            ]
        }
    ]
}

这有什么问题?

也许这是其他的东西。其余代码是:

    var chart;      //The chart
var options;    //The options for the chart
var data;       //The data inside the chart

//This function will set up the actual chart but doesn't draw it.           
function init(){
    chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    options = {
        width:600, height:450,      
        legend: {'position': 'top'},
        allowHtml: true
    };                      
}

function changeData(dataPar){
    data = new google.visualization.DataTable(dataPar);
    drawChart();                  
}

function drawChart(){   
    chart.draw(data, options);
}                   

JSON对象在函数changeData()中抛出。

我在ajax部分得到了这个:

    dataType: "json",       
    success: function(res, textStatus, jqXHR){
       changeData(res);
    }

我收到红色背景错误:

  

a [dc]不是函数

有人知道出了什么问题,解决方案应该是什么?

1 个答案:

答案 0 :(得分:1)

好吧,我自己想通了。

在cols中,我将列“date”的类型设置为date,但它必须是一个字符串,因为给定的值是一个字符串。

因此,如果您从google visualization charts收到奇怪的错误,那么您的json部分可能会出现错误,JSONLint似乎有效。

我调试json部分的建议是首先使用addColumn()和addRows()函数创建一个虚拟DataTable然后执行

console.log([DataTable var].toJSON()).

将此输出与您使用先前脚本和调试创建的JSON进行比较。

我有以下JSON对象:

{
    "cols": [
        {"id": "date", "label": "date","pattern": "","type": "string"},
        {"id": "newjobs","label": "newjobs","pattern": "","type": "number"}
    ],
    "rows": [
        {"c": [
                {"v": "01-02-2013","f": null},
                {"v": 132,"f": null}
            ]},
        {"c": [
                {"v": "08-02-2013","f": null},
                {"v": 78,"f": null}
            ]},
        {"c": [
                {"v": "15-02-2013","f": null},
                {"v": 105,"f": null}
            ]
        },
        {"c": [
                {"v": "22-02-2013","f": null},
                {"v": 8,"f": null}
            ]}
    ]
}