首页 > 解决方案 > 使用 JSON 的基本 Highcharts 多系列图表

问题描述

我正在尝试创建一个基本折线图,其中包含 json 文件中的三个系列数据。json 文件是json.json此示例的名称。我已经使用JSON Formatter验证了 JSON 格式。

JSON 格式示例

{
"Series1 (Units1)": [100 ,200 ,300],
"Series2 (Units2)": [10, 20, 30],
"Series3 (Units3)": [1, 2, 3]
}

当前使用的代码来自我发现的另一个示例

$(function () {

    $.getJSON('data/json.json', function (data) {
        console.log(data)
        var processedData = [];
        Highcharts.each(data, function (d) {
            processedData.push(d.Series);
        });

        // Create the chart
        $('#container').highcharts('StockChart', {
            rangeSelector: {
                selected: 1
            },
            title: {
                text: 'Series'
            },

            series: [{
                data: processedData
            }]

        });
    });

});

我已经模拟了我尝试使用JSFiddle实现的图表示例。

我还尝试从另一篇文章中跟随这个JSFiddle,但是当我尝试修改它时 JSON 数据不会加载。

我已经通过添加该行来检查是否正在获取数据console.log(data)

如何使用这种格式将数据加载到图表中?

标签: highcharts

解决方案


You have to convert you JSON from key: value to proper series format, which in your case is something similar to:

[{ 
    name: 'my series', 
    data: [1,2,3] 
}, ...];

Currently your processedData formatting is not correct, so the end result put into Highcharts series is invalid.

In, short, your events GET, process and display could look something like this (CodePen):

$(function () {
    $.getJSON('https://api.myjson.com/bins/yu6gq', function (data) {
        var processedData = [];

        for(var entry in data) {
            processedData.push({
              name: entry,
              data: data[entry]
            });
        }

        // Create the chart
        $('#container').highcharts('StockChart', {
            series: processedData
        });
    });
});

Its still just the task of creating the proper processedData array, containing Series objects with the correct format. In this example each Series is given the name and data attributes, filled in with values from your JSON.


推荐阅读