Stephen305
Stephen305

Reputation: 1097

How to build JSON object with nested JSON objects

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'}}};

Upvotes: 0

Views: 9758

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123387

var 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" : [ ]};

Upvotes: 4

RoboKozo
RoboKozo

Reputation: 5062

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.com/en-us/library/cc836459(v=vs.85).aspx

https://developer.mozilla.org/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.org/js.html

Upvotes: 3

Related Questions