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

4 Answers 4

Reset to default 4

You 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