Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  113] [ 3]  / answers: 1 / hits: 19049  / 11 Years ago, tue, march 12, 2013, 12:00:00

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'
]
}

More From » json

 Answers
52

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.


[#79651] Monday, March 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zaynerogerb

Total Points: 454
Total Questions: 109
Total Answers: 97

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
zaynerogerb questions
;