Jane WIlkie Jane WIlkie - 4 months ago 72
Javascript Question

Loading JSON into a Highcharts pie chart

I think what I probably have is a simple problem. This works great ..


$(document).ready(function() {
// Original data
var data = [{
"name": "Tokyo",
"y": 3.0
}, {
"name": "NewYork",
"y": 2.0
}, {
"name": "Berlin",
"y": 3.5
}, {
"name": "London",
"y": 1.5
}];
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie'
},
series: [{
data: data
}]
});
});


I wanted to modify the code to load using getJSON and the JSON is formatted correctly.
So I did this...


$(document).ready(function() {
$.getJSON("etstats?rtype=bestpgs_ec&month=2016-06-01&no_requested=10", function(json){
var data = json
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie'
},
series: [{
data: data
}]
});
});
});


I checked the JSON in Firebug and it's formatted correctly using "name" and "y"


[{"name": "14704", "y": "0.17"}, {"name": "14706", "y": "0.20"}, {"name": "21304", "y": "0.25"}, {"name"
: "23201", "y": "0.39"}, {"name": "23501", "y": "0.42"}, {"name": "17102", "y": "0.46"}, {"name": "15001"
, "y": "0.48"}, {"name": "23002", "y": "0.50"}, {"name": "13201", "y": "0.50"}, {"name": "17401", "y"
: "0.52"}]


Does anyone have any pointers as to why my chart won't render?

Note: Edited to add answer. The quoted values were the issue. They are removed by iterating over them and eval the value.


$.getJSON("etstats?rtype=bestpgs_ec&month=2016-06-01&no_requested=10", function(json){
data = json
$.each(data, function (i, point) {
point.y = eval(point.y);
});
var chart = new Highcharts.Chart({

Answer

I use the data given above. I think highchart just doesn't accept string type in y

here is the demo

a valid JSON format should be

[
  {"name":"14704","y":0.17},
  {"name":"14706","y":0.2},
  {"name":"21304","y":0.25},
  {"name":"23201","y":0.39},
  {"name":"23501","y":0.42},
  {"name":"17102","y":0.46},
  {"name":"15001","y":0.48},
  {"name":"23002","y":0.5},
  {"name":"13201","y":0.5},
  {"name":"17401","y":0.52}
]

after your getJSON complete, remember doing JSON.parse first to get the correct object and then you can finally pass it into highchart