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'
]
}
Well, you have two options:
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With