I am constructing a JSON object with nested objects in Javascript. Is there an easy way to do this in Javascript without using eval()?
var data_json = "data = {'"+field_name+"':{'answers':{";
for(var i=0; i<answers.length; i++){
data_json += "'" + i + "':" + "'" + answers[i] + "',";
}
data_json = data_json.replace(/,$/,"");
data_json = data_json + "}}}";
eval(data_json);
Result:
data={'myfield':{'answers':{'0':'The answer', '1':'Another answer'}}};
As a side note, if
data[field_name]["answers"]contains numeric keys only, it should be an array and not an object, sodata[field_name]should be= { "answers" : [ ]};