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'}}};
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'}}};
Share
Improve this question
edited Apr 13, 2012 at 16:19
Stephen305
asked Apr 13, 2012 at 15:53
Stephen305Stephen305
1,0973 gold badges22 silver badges30 bronze badges
3
- why are you constructing json in javascript, javascript IS json – dstarh Commented Apr 13, 2012 at 15:55
- I'm not sure what you mean. JSON is "JavaScript Object Notation". It is a language-independent data interchange format. – Stephen305 Commented Apr 13, 2012 at 16:10
- Correct i should have expanded on what i was saying. JavaScript objects are json, there's no need to use string concat just build the object graph as is done in the selected answer – dstarh Commented Apr 13, 2012 at 18:03
2 Answers
Reset to default 4var a, data = {};
data[field_name] = { "answers" : { } };
a = data[field_name]["answers"];
for(var i=0; i<answers.length; i++){
a[i] = answers[i];
}
console.log(data);
As a side note, if data[field_name]["answers"]
contains numeric keys only, it should be an array and not an object, so data[field_name]
should be = { "answers" : [ ]};
Personally, I'd use JSON.stringify to convert your javascript objects into a json string format.
Check these out for more information.
http://msdn.microsoft./en-us/library/cc836459(v=vs.85).aspx
https://developer.mozilla/en/JavaScript/Reference/Global_Objects/JSON/stringify
You can also use JSON.parse to go the other way (from string to object)
var myObject = JSON.parse(myJSONtext, reviver);
http://www.json/js.html