简体   繁体   English

从HighCharts中的JSON动态添加类别和系列

[英]Add Categories and Series dynamically from JSON in HighCharts

Please consider this JSON : 请考虑以下JSON

[
   {
      "Categories": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
   },
   {
      "SeiresName": "Ava",
      "Data": ["49.9", "71.5", "106.4", "129.2", "144.0", "176.0", "135.6", "148.5", "216.4", "194.1", "95.6", "54.4"]
   },
   {
      "SeiresName": "Nima",
      "Data": ["83.6", "78.8", "98.5", "93.4", "106.0", "84.5", "105.0", "104.3", "91.2", "83.5", "106.6", "92.3"]
   },
   {
      "SeiresName": "Arian",
      "Data": ["48.9", "38.8", "39.3", "41.4", "47.0", "48.3", "59.0", "59.6", "52.4", "65.2", "59.3", "51.2"]
   }
]

I want to create a Column chart and add write code: 我想创建一个Column并添加编写代码:

   $(function () {
        $.getJSON('JSON Data/ColumnchartWithSeries.json', function (data) {
            console.log(data);
            $('#container').highcharts({
                chart: {
                    type: 'column'
                },
                title: {
                    text: 'Title'
                },
                xAxis: {
                    categories: [],
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: 'Y-Axis Title'
                    }
                },
                legend: {
                    reversed: true
                },
                series: [{}]
            });
        });
    });

I don't know how I can assign Categories and add series dynamically.How I can do this? 我不知道如何分配Categories并动态添加系列,我该怎么做?

Thanks 谢谢

You have to process JSON string 您必须处理JSON字符串

var categories = []; //categories array to highchart
var seriesData = []; //series object to highchart

for (var i = 0; i < jsondata.length; i++) {
  if (jsondata[i].Categories) {
    categories = jsondata[i].Categories.replace(/\[|]|'/g, '').split(',')
  }
  if (jsondata[i].SeiresName) {
    seriesData.push({
      name: jsondata[i].SeiresName,
      data: JSON.parse(jsondata[i].Data)
    })
  }
}

Fiddle working demo 小提琴工作演示

Update Change in JSON Data updated accordingly 更新 JSON数据中的更改已相应更新

for (var i = 0; i < jsondata.length; i++) {
  if (jsondata[i].Categories) {
    categories = jsondata[i].Categories
  }
  if (jsondata[i].SeiresName) {
    seriesData.push({
      name: jsondata[i].SeiresName,
      data: jsondata[i].Data.map(Number)
    })
  }
}

Updated Fiddle 更新小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM