...

View Full Version : Dynamically Creating JSON



mark007
11-25-2008, 12:51 PM
Hi all,

I have a form with multiple fields (around 50) which I need to store to sql database. I have some nice php code that can take my json id value pairs and add it to the correct fields in the mysql database.

All I need to give it is valid json and it does the rest. My problem is creating json for this large collection of fields without doing it manually.

So my json object needs to be made from dom id, value pairs from nodes with classname input.

# I can get this list of input fields like this

var list=dojo.query(".input");

# I can then get their ids and values in a loop like this

for (var i=0;i<list.length;i++)
{
var id=list[i].id;
var value=list[i].value;
}

How can I create an object of the following structure, using the loop above or is it possible?

var data={
orderer_id: dojo.byId("orderer_id").value,
final_comments_id: dojo.byId("final_comments_id").value
...,
...
};

If I can create this data object on the fly without manually specifying any fields in it, I can then use the method below to convert it to perfect json.

var json_of_data=dojo.toJson(data);

Thanks for any suggestions,
Mark

rnd me
11-25-2008, 01:01 PM
repetitive data gets an array of simply objects:



var list=dojo.query(".input");
var dynOb = [];

for (var i=0;i<list.length;i++){
var data={
orderer_id:list[i].id,
final_comments_id: list[i].value
};
dynOb[i] = data;
}

mark007
11-25-2008, 02:01 PM
what i need in my data object is what needs to be created dynamically, both values and variable names so

data={
var_name:value_name;
var_name:value_name;
var_name:value_name;
var_name:value_name;
var_name:value_name;
var_name:value_name;
var_name:value_name;
var_name:value_name;
var_name:value_name;
}

It is these "var_name"' s that I will be getting from the dojo.query(), and the value's also.

I do not know how to dynamically add different variables to the data object. Any ideas how I could manage this?

rnd me
11-25-2008, 02:05 PM
ahh, i see.

something along the lines of this should work:



var data = {};

for loop begin
data[list[i].id] = list[i].value
for loop end

make sense?

mark007
11-25-2008, 02:19 PM
Amazingly easy! Thanks so much!

I love JSON :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum