Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  95] [ 2]  / answers: 1 / hits: 118298  / 14 Years ago, tue, november 30, 2010, 12:00:00
var myJSON = {  
list1 : [ 1, 2 ],
list2 : [ a, b ],
list3 : [ { key1 : value1 }, { key2 : value2 } ],
not_a_list : 11
};


How do I dynamically build this JSON structure in javascript? Google tells me to use use some push command, but I've only found specific cases. So what do I write to enter data to listX and not_a_list. Appending as well as creating a new list. The whole procedure begninning with:



var myJSON = {};

More From » javascript

 Answers
22

First, I think you're calling it the wrong thing. JSON stands for JavaScript Object Notation - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is object.



With that pedantry out of the way, I think that you're asking how to set object and array properties.



// make an empty object
var myObject = {};

// set the list1 property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';


That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.


[#94793] Saturday, November 27, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dustin

Total Points: 599
Total Questions: 105
Total Answers: 106

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
dustin questions
;