admin管理员组文章数量:1428481
Is there a way to create a JSON object ID with a variable?
var json_result = [];
var id = 20;
json_result.push({id: {parentId: parentId, position: position}});
This results into a json object with the value 'id' as the id. I want to achieve to have the value '20' as the key.
EDIT: Include solution:
var json_result = {};
var id = 20;
json_result[id] = {parentId: parentId, position: position};
Now you can access parentId and position like this:
json_result[20].position
json_result[20].parentId
Is there a way to create a JSON object ID with a variable?
var json_result = [];
var id = 20;
json_result.push({id: {parentId: parentId, position: position}});
This results into a json object with the value 'id' as the id. I want to achieve to have the value '20' as the key.
EDIT: Include solution:
var json_result = {};
var id = 20;
json_result[id] = {parentId: parentId, position: position};
Now you can access parentId and position like this:
json_result[20].position
json_result[20].parentId
Share
Improve this question
edited Jul 30, 2012 at 15:37
Thomas Kremmel
asked Jul 30, 2012 at 14:52
Thomas KremmelThomas Kremmel
14.8k26 gold badges112 silver badges178 bronze badges
1
- That's a JavaScript object, not a JSON object. – gen_Eric Commented Jul 30, 2012 at 14:56
4 Answers
Reset to default 4You cannot write such an object literal (it's not a "JSON object" by the way; just a plain Javascript object), but you can do it like this:
var o = {};
o[id] = {parentId: parentId, position: position};
json_result.push(o);
var json_result = [];
var id = 20;
var obj = {};
obj[id] = "something";
json_result.push(obj);
This is one of the reasons the JSON spec says that keys should be strings. Your JSON should really look like this:
{
"20": {
"parentId": ...,
"position": ...}
}
... or similar. Check out http://json/example.html
Yes, you can do it like this:
var obj = {};
obj[id] = {parentId: parentId, position: position};
json_result.push(obj);
本文标签: javascriptjsoncreate json object id based upon variableStack Overflow
版权声明:本文标题:javascript - json - create json object id based upon variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745501613a2661057.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论