最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to build JSON object with nested JSON objects - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4
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" : [ ]};

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

发布评论

评论列表(0)

  1. 暂无评论