Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I build JSON dynamically in javascript?

Tags:

javascript

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 = {}; 
like image 383
Saftsoppa Avatar asked Nov 30 '10 12:11

Saftsoppa


People also ask

What is a dynamic JSON?

A dynamic JSON file will be created to store the array of JSON objects. Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails. json by converting them into an array of JSON objects.

What is toJSON () in JSON?

The toJSON() method returns a date object as a string, formatted as a JSON date.


2 Answers

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.

like image 155
Neall Avatar answered Sep 30 '22 02:09

Neall


As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"]; 

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"]; 

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3"); 
like image 39
AndreKR Avatar answered Sep 30 '22 02:09

AndreKR