Ajax JSON in to Highcharts Pie Chart

2020-07-27 02:45发布

问题:

I have been encountering issues for the past few days with ajaxing in some sample json data from an external file to populate a pie chart using the Highcharts library.

Here is my sample JSON data in file: data.json

   [
     ["Apples", 43.0],
     ["Pears", 57.0]
   ]

Here is my implementation of highcharts and my AJAX call: (I have omitted unrelated code)

<script type="text/javascript">
     $(function() {
       var options = {
            chart: {
                renderTo: 'Chart',
                defaultSeriesType: 'pie'
            },
            title: {
               text:'Fruits'
             },

            plotOptions: {
                 pie: {
                     allowPointSelect: true,
                     cursor: 'pointer',
                     dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',

                     }
                 }
            },
            series: [{
               type: 'pie',
               name: 'Fruits',
               data: []
            }]
         };

        $.getJSON('data.json', function(json) {

           options.series.push(json);               
           var chart = new Highcharts.Chart(options);
         }).error(function() {console.log('error');});


     });
</script>

Basically, I want to pass in the JSON, into options.series[].data[]. When proceed with

options.series.push(json);

I get:

[Object, Array[2]] // where the Object contains .name and .type and the Array[2] is my data

I'm pretty sure I need this:

[Object] // which contains .data , .name, .type

回答1:

I was actually able to solve my problem by structuring my JSON like so:

[
     {
          "type" : "pie",
          "name" : "Fruits",
          "data" : [
               [
                    "Apple",
                     43.0
               ],
               [  
                    "Pear",
                    "57.0"
               ]
           ]
     }
]

and instead of doing an array push,

I set the series parameter to the JSON like this:

 $.getJSON("data.json", function(json)) {
    options.series = json;
    var chart = new Highcharts.chart(options);
 }


回答2:

Just in case anyone else runs across this like I did. I solved the same problem with series.data.push as series is an array also, highcharts would not have known we were actually trying to push the value into data instead.