如何将Date值从JSON返回到Google Visualization API

cil*_*ler 10 datatable json date google-visualization

有没有办法从Google Visualization API中的JSON中检索日期值?这是操场 上的小贴士,请将下面的代码复制到其中

当您运行代码时,您将无法获得任何结果.您应该从我标记为注释的日期值中删除引号,以便检索结果.

function drawVisualization() {
var JSONObject = {
cols:
    [
        {id: 'header1', label: 'Header1', type: 'string'},
        {id: 'header2', label: 'Header2', type: 'date'}
    ],
rows: 
    [
        {
            c:
                [
                    {v: 'Value1'}, 
                    {v: "new Date(2010, 3, 28)"}  // <= This is the format I receive from WebService
                ]
        },
        {
            c:
                [
                    {v: 'Value2'},
                    {v: new Date(2010, 3, 28)} // <=This is the format Google API accepts
                ]
        }
    ]
};

var data = new google.visualization.DataTable(JSONObject, 0.5);

visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {'allowHtml': true});
}
Run Code Online (Sandbox Code Playgroud)

Jan*_*iak 9

我自己也遇到了这个问题,所以我想我会粘贴来自google api文档的答案,位于http://code.google.com/apis/chart/interactive/docs/dev/implementing_data_source.html#jsondatatable

"JSON不支持JavaScript Date值(例如,"new Date(2008,1,28,0,31,26)"; API实现可以.但是,API现在支持日期的自定义有效JSON表示形式以下格式的字符串:日期(年,月,日[,小时,分钟,秒[,毫秒]]),其中一天之后的所有内容都是可选的,而月份则从零开始."


VGE*_*VGE 0

我认为引用不在您的代码片段中的正确位置,"new Date(2010, 3, 28") 请改为写入"new Date(2010, 3, 28)"

Json 格式不接受 javascript 对象,因此服务器返回一个字符串。JSON 只知道数字、布尔常量、字符串、null、向量和“对象”(更多的是字典)。

我想您必须对返回的字符串执行 eval() (不要忘记检查输入)。

另一种选择是使用正则表达式来提取类似的字段/new Date\((\d+),(\d+),(\d+)\)/