JSON Parse for Highcharts

时间:2013-01-06 05:08:35

标签: javascript json highcharts highstock

我看过很多例子。然而,我仍然坚持这一点。如何解析此JSON响应以使用我的Highstock Highchart?

[{"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
        }]
    });
});

2 个答案:

答案 0 :(得分:0)

Axis和数据需要数组。请尝试:

$.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;
              }() 
        }]
    });
});

答案 1 :(得分: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');