2013-01-06 68 views
-1

我已經看了很多例子。然而,我仍然堅持這一點。我如何解析這個JSON響應以與我的Highstock Highchart一起工作?JSON解析爲Highcharts

[{"averageprice":"18.7","date":"2000-01-01"},{"averageprice":"41.73","date":"2000-01-02"},{"averageprice":"34.27","date":"2000-01-03"},{"averageprice":"30.06","date":"2000-01-04"}] 

這裏是我的圖表到目前爲止...

$.getJSON('http://example.com/dailyaverages.json', function(data) { 
    // Create the chart 
    window.chart = new Highcharts.StockChart({ 
     chart : { 
      renderTo : 'ppcontent' 
     }, 

     rangeSelector : { 
      selected : 0 
     }, 

     title : { 
      text : 'Trade Prices' 
     }, 

     xAxis: { 
      type: 'datetime' 
     }, 
     series : [{ 
      data : data 
     }] 
    }); 
}); 
+0

大多數現代瀏覽器都支持'JSON.parse()'方法,它的名字的確如此。 – 2013-01-06 05:29:14

回答

0

軸和數據的預期陣列。請嘗試:

$.getJSON('http://example.com/dailyaverages.json', function(data) { 
    // Create the chart 
    var dataObj = JSON.parse(data); 
    window.chart = new Highcharts.StockChart({ 
     chart : { 
      renderTo : 'ppcontent' 
     }, 

     rangeSelector : { 
      selected : 0 
     }, 

     title : { 
      text : 'Trade Prices' 
     }, 

     xAxis: { 
      type: 'datetime' 
     }, 
     series : [{ 
      name: "Trade Prices", 
      data : function() { 
        var dataArr = []; 
        dataObj.forEach(function(d) { 
        dataArr.push(parseInt(d.averageprice, 10)); 
        }); 
        return dataArr; 
       }() 
     }] 
    }); 
}); 
+0

謝謝Munish。這看起來很接近,但它返回了錯誤。 「未捕獲的SyntaxError:意外的令牌o」。我的控制檯指向這一行:var dataObj = JSON.parse(data); – ac360

+0

我認爲getJSON函數的第二個參數是要發送到服務器的數據。如果沒有東西要發送,那麼你可以傳遞null。所以,你的第一行看起來像這樣:'$ .getJSON('http://example.com/dailyaverages.json',null,function(data){' –

0

以下是我的工作。必須將日期轉換爲UNIX格式:

function addPriceChart(chartcontainerID, chartTitle, dataURL) { 
      $.getJSON(dataURL, function (jsonresult) { 

      window.chart = new Highcharts.StockChart({ 
       chart: { 
       renderTo: chartcontainerID 
       }, 

       rangeSelector: { 
       selected: 1 
       }, 

       title: { 
       text: chartTitle 
       }, 

       credits: { 
       enabled: false 
       }, 

       series: [{ 
       name: 'Price1', 
       data: function() { 
        var dataArr = []; 
        jsonresult.forEach(function (row) { 
        var dateParts = row.date.split('-'); 
        var date = new Date(dateParts[0], (dateParts[1] - 1), dateParts[2]); 
        var data = [date.getTime(), parseFloat(row.averageprice)]; 
        dataArr.push(data); 
        }); 
        return dataArr; 
       }(), 
       tooltip: { 
        valueDecimals: 2 
       } 
       }] 
      }); 
      }); 
    } // END addPriceChart Function 


    addPriceChart('ppcontent', 'Prices, 'http://mysite.com/data.json');