如何将数据从JSON加载到Highchart?

时间:2012-03-30 10:24:20

标签: javascript json highcharts

我的 Json 如下所示:

[{"1332879360000.0": 300.0, "1332797760000.0": 353.0,

"1332799320000.0": 358.0, "1332879780000.0": 302.0, 

"1332800160000.0": 359.0, "1332880200000.0": 299.0, 

"1332880620000.0": 298.0, "1332881040000.0": 301.0, 

"1332881460000.0": 402.0, "1332880020000.0": 330.0, 

"1332882300000.0": 466.0, "1332796620000.0": 519.0, 

"1332800520000.0": 447.0, "1332797460000.0": 359.0, 

"1332801000000.0": 442.0}]

我想在Highchart中显示这些数据,X轴是日期格式,

("1332801000000.0" in JSON)和Y轴是数据(300.0 in JSON)

就像一点。

我注意到Highchart.com中有一个演示,它运行实时数据。我复制了那个,但我不想表现得很生动。只需一次显示这些点,然后组成一个图表。有解决方案吗我对JavaScript不太熟悉。但我认为这可能使用相同的方法。

<script type="text/javascript">
    var chart; // global

    /**
     * Request data from the server, add it to the graph and set a timeout to request again
     */
    function requestData() {
        $.ajax({
            url: '/get_data', 
            success: function(point) {
                var series = chart.series[0],
                    shift = series.data.length > 20; // shift if the series is longer than 20

                // add the point
                chart.series[0].addPoint(eval(point), true, shift);


                // call it again after one second
                setTimeout(requestData, 5000);  
            },
            cache: false
        });
    }

    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'test',
                defaultSeriesType: 'spline',
                events: {
                    load: requestData
                }
            },
            title: {
                text: 'Live random data'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150,
                maxZoom: 20 * 1000
            },
            yAxis: {
                minPadding: 0.2,
                maxPadding: 0.2,
                title: {
                    text: 'Value',
                    margin: 80
                }
            },
            series: [{
                name: 'Random data',
                data: []
            }]
        });



    });
    </script>

4 个答案:

答案 0 :(得分:1)

我不确定理解你的问题......所以,如果我误解了,请纠正我。

您只需将your json data复制到名称为example.json的文件中,然后在您的ajax请求中进行以下操作:

function requestData() {
    $.ajax({
        url: './example.json',  // depending which directory you save your file
        // the other code
  });
};

答案 1 :(得分:0)

试试这个     

}
// Set the JSON header
header("Content-type: text/json");

// The x value is the current JavaScript time, which is the Unix time multiplied by       1000.
$x = time() * 1000;
$y = rand(0,100) ; 
mysql_query("INSERT INTO `apak`.`mach_1` (`id`, `temp`, `date_time`) VALUES           (NULL,'".$y."', CURRENT_TIMESTAMP);") ; 


// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>

现在是高图脚本

<script>
 /**
 * Request data from the server, add it to the graph and set a timeout to request again
 */
var chart; // global
function requestData() {
$.ajax({
    url: 'http://localhost:8080/test.php',
    success: function(point) {
        var series = chart.series[0],
            shift = series.data.length > 20; // shift if the series is longer than 20

        // add the point
        chart.series[0].addPoint(point, true, shift);

        // call it again after one second
        setTimeout(requestData, 1000);    
    },
    cache: false
   });
 }
 $(document).ready(function() {
   chart = new Highcharts.Chart({
      chart: {
        renderTo: 'container',
        defaultSeriesType: 'spline',
        events: {
            load: requestData
        }
    },
    title: {
        text: 'Live random data'
    },
    xAxis: {
        type: 'datetime',
        tickPixelInterval: 100,
        maxZoom: 20 * 1000
    },

    yAxis: {
        minPadding: 0.2,
        maxPadding: 0.2,
        title: {
            text: 'Value',
            margin: 80
        }
    },
    series: [{
        name: 'Random data',
        data: []
     }]
   });        
});
  </script>
  <  /head>
<body>

</div>
</body>
</html>

答案 2 :(得分:0)

以下是解决方案的最小工作示例。您可以使用Object.keys和Array.prototype.map解析数据对象,最后要使用Array.prototype.sort对数据数组进行排序。

const json = [{
  "1332879360000.0": 300.0,
  "1332797760000.0": 353.0,
  "1332799320000.0": 358.0,
  "1332879780000.0": 302.0,
  "1332800160000.0": 359.0,
  "1332880200000.0": 299.0,
  "1332880620000.0": 298.0,
  "1332881040000.0": 301.0,
  "1332881460000.0": 402.0,
  "1332880020000.0": 330.0,
  "1332882300000.0": 466.0,
  "1332796620000.0": 519.0,
  "1332800520000.0": 447.0,
  "1332797460000.0": 359.0,
  "1332801000000.0": 442.0
}]

const options = {
  xAxis: { type: 'datetime' },
  series: [{
    // Get array of keys from your json object
    data: Object.keys(json[0])
      // Map your keys to arrays with x and y values
      .map((key) => [Number(key), json[0][key]])
      // Sort your data
      .sort((a, b) => a[0] - b[0]),
  }]
}

const chart = Highcharts.chart('container', options);

实例:https://jsfiddle.net/33hd8jog/

[编辑]

我还使用从服务器获取数据创建了一个示例:

const url = 'https://rawgit.com/stpoa/7d44ff0db61515dae80ad021b7c6c01a/raw/800735764d6596512a5fbc69acad019ed0416d8f/data.json'

window.fetch(url).then(response => response.json()).then(json => {
  const options = {
    xAxis: { type: 'datetime' },
    series: [{
      // Get array of keys from your json object
      data: Object.keys(json[0])
        // Map your keys to arrays with x and y values
        .map((key) => [Number(key), json[0][key]])
        // Sort your data
        .sort((a, b) => a[0] - b[0]),
    }]
  }

  const chart = Highcharts.chart('container', options)
})

实例:https://jsfiddle.net/gxb6j2tz/

答案 3 :(得分:-1)

我在使用JSON的javascript中完成了这个..

"onResultHttpService": function (result, properties) {

            var json_str = Sys.Serialization.JavaScriptSerializer.deserialize(result);
            var data = [];
            var cat = [];

            var categoryField = properties.PodAttributes.categoryField;
            var valueField = properties.PodAttributes.valueField;
            for (var i in json_str) {
                var serie = new Array(json_str[i][categoryField], json_str[i][valueField]);
                var tmpCat = new Array(json_str[i][categoryField]);
                data.push(serie);
                cat.push(tmpCat);
            }
            //cat = 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'

            chart = new Highcharts.Chart({
                chart: {
                    renderTo: properties.id,
                    type: 'column'
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: ''
                },
                xAxis: {
                    categories: cat
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: ''
                    }
                },
                legend: {
                    layout: 'vertical',
                    backgroundColor: '#FFFFFF',
                    align: 'left',
                    verticalAlign: 'top',
                    x: 100,
                    y: 70,
                    floating: true,
                    shadow: true
                },
                tooltip: {
                    formatter: function () {
                        return '' +
                    this.x + ': ' + this.y + ' mm';
                    }
                },
                plotOptions: {
                    column: {
                        pointPadding: 0.2,
                        borderWidth: 0
                    }
                },
                series: [{ data: data}]
            });


        }

    };