Thomas Kremmel
Thomas Kremmel

Reputation: 14783

json - create json object id based upon variable

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

Upvotes: 1

Views: 5018

Answers (4)

codebox
codebox

Reputation: 20254

Yes, you can do it like this:

var obj = {};
obj[id] = {parentId: parentId, position: position};
json_result.push(obj);

Upvotes: 0

jonathan.cone
jonathan.cone

Reputation: 6706

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.org/example.html

Upvotes: 0

Tom
Tom

Reputation: 4180

var json_result = [];
var id = 20;
var obj = {};
obj[id] = "something";
json_result.push(obj);

Upvotes: 1

Jon
Jon

Reputation: 437604

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);

Upvotes: 4

Related Questions