Jason
Jason

Reputation: 195

HIghcharts and dynamic json

Im using a php to pass json to Highcharts. My php is returning json that looks like this:

{"A":5,"B":12,"C":5,"D":11,"E":6}

How would I go about building a chart with the categories: A,B,C,D,E and the Values: 5,12,5,11,6?

I've tried using:

$.getJSON("test.php", function(json){
            $.each(json, function(i, e) {
             options.series.data= json;
                });
            chart = new Highcharts.Chart(options);

            });

I know this is just taking all of the json and trying to dump it in the series.data which is wrong. What is the best way to split up the keys and values? Should this be handled on the php side or in javascript?

Thanks

Upvotes: 0

Views: 143

Answers (1)

Buzinas
Buzinas

Reputation: 11725

I've create a class for you, so you can use it anywhere:

HighChartObject = function (obj) {
    if (typeof obj === 'string') obj = JSON.parse(obj);

    for (var key in obj) {
        this[key] = obj[key];
    }
}

HighChartObject.prototype.getDataArray = function () {
    var arr = [];

    for (var key in this) {
        if (this.hasOwnProperty(key)) {
            arr.push(obj[key]);
        }
    }

    return arr;
}

HighChartObject.prototype.getCategoriesArray = function () {
    var arr = [];

    for (var key in this) {
        if (this.hasOwnProperty(key)) {
            arr.push(key);
        }
    }

    return arr;
}

Usage:

var json = '{ "A": 5, "B": 12, "C": 5, "D": 11, "E": 6 }';
var obj = new HighChartObject(json);

$("#container").highcharts({
    xAxis: {
        categories: obj.getCategoriesArray()
    },
    series: [
        {
            name: "MyName",
            data: obj.getDataArray()
        }
    ]
});

And here there is a FIDDLE, so you can play with it!

I don't know if this is exactly what you need, but I think you can improve the code for your needs, right?

I hope it can help you =)

Upvotes: 2

Related Questions