Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create the following type of json array using javascript?

How to create the following type of json array using javascript?

xAxis: {
    categories: [
        'Jan',
        'Feb',
        'Mar',
        'Apr',
        'May',
        'Jun',
        'Jul',
        'Aug',
        'Sep',
        'Oct',
        'Nov',
        'Dec'
    ]
}
like image 711
Jetson John Avatar asked Mar 12 '13 08:03

Jetson John


1 Answers

Well, you have two options:

  1. Create the array and then stringify it:

    var categories = [
                'Jan',
                'Feb',
                'Mar',
                'Apr',
                'May',
                'Jun',
                'Jul',
                'Aug',
                'Sep',
                'Oct',
                'Nov',
                'Dec'
            ];
    var json = JSON.stringify(categories);
    

    JSON.stringify exists on most modern browsers, and you can shim it. (There are several shims available, not least from Crockford's github page -- Crockford being the person who defined JSON.)

  2. Or just create the JSON string directly:

    var json = '["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]';
    

Re your edit: That's not "an array" anymore, it's an object with an array in it (or an object with an object in it with an array in that). It doesn't fundmentally change the answer, though:

var xAxis = { categories: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] };
var json = JSON.stringify(xAxis);

or

var json = '{"categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]}';

I wasn't sure whether you wanted the xAxis layer in there. If so, it's just another layer around the above, e.g.:

var obj = { xAxis: { categories: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] } };
var json = JSON.stringify(obj);

or

var json = '{"xAxis": {"categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]}}';

More about JSON on the JSON home page. Fundamentally, all strings must be in double (not single) quotes, and all property names must be in double quotes.

like image 169
T.J. Crowder Avatar answered Oct 24 '22 16:10

T.J. Crowder