在Google Charts中从JSON动态填充数据

时间:2015-07-01 08:49:12

标签: javascript google-visualization google-chartwrapper

    My JSON data: 

    {"price":1.0,"bookName":"ABC","time":"10:0"},{"price":1.0,"bookName"
    :"DEF","time":"10:0"},{"price":1.0,"bookName":"ERT","time":"10:0"},{"price":1.0,"bookName":"JKL","time":"10:0"},{"price":0.25,"bookName":"ABC","time":"10:05"},{"price"
    :0.25,"bookName":"DEF","time":"10:05"},{"price":0.25,"bookName"
    :"ERT","time":"10:05"},{"price":0.25,"bookName":"JKL","time":"10:05"}

    JS Code: 

    WHen i hardcode the value like below then i am able to display the chart.

    google.load('visualization', '1.1', {packages: ['corechart']});
    google.setOnLoadCallback(drawChart);

     function drawChart(){

      var data = new google.visualization.arrayToDataTable([
        ['Time', 'ABC', 'DEF', 'ERT', 'JKL'],
          ['10:0',  1.0,      0.25,         0.25,             1.0          ],
          ['10:0',  1.0,      1.0,        1.0,             1.0          ],
          ['10:0',  0.25,      0.25,        0.25,             0.25],
          ['10:0',  1.0,      0.25,        0.25,             0.25],
          ['10:05',  1.0,      0.25,         1.0,             0.25],
          ['10:05',  0.25,     1.0,         0.25,             1.0],
          ['10:05',  0.25,      0.25,         0.25,             0.25],
          ['10:05',  0.25,      0.25,         0.25,             0.25],
             ]);

    I would like to know how to create the data like above dynamically using JSON object. I have tried the below code so far.

这里的问题是我必须动态生成列,即从JSON对象生成。 bookname将永远是4提到的,只是它们的价格会在不同的时间变化。

resultObj是从后端获取的实际JSON对象名称。

我想知道如何进一步创建行数据。

请指导我。如果需要,我可以添加更多细节。

1 个答案:

答案 0 :(得分:0)

您在JSON上使用了错误的格式,谷歌图表具有用于接收数据的特定布局,请阅读更多here

您的数据必须如下所示:

{
  cols:[{label:'Bookmark', type:'string'}, 
        {label:'Price', type:'number'}, 
        {label:'time', type:'number'}
       ],
  rows:[{c:[{v:'ABC'}, {v:1.0}, {v:10.0}]},
         c:[{v:'DEF'}, {v:1.0}, {v:10.0}]},
       }]
}

所以你必须像这样动态排列它们,以便能够将整个JSON传递给你的图表。

我做了一个小fiddle.