1

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
1
  • That's a JavaScript object, not a JSON object. Commented Jul 30, 2012 at 14:56

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. This works. But I thought I should be able to access the value then like this: console.log(json_result[20]); But it does not work. Any idea what I have to change? Basically I want to access the parentid and position of the id 20 without looping over the entire array.
@TomTom: When you are pushing o into json_result you are not giving it a key equal to id. If you want to do that, simply use o as your json_result and remove all references to the original json_result (which is an array; you don't want that, based on the comment).
Thanks, now I got it. Included the solution in my question.
1
var json_result = [];
var id = 20;
var obj = {};
obj[id] = "something";
json_result.push(obj);

Comments

0

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

1 Comment

He's trying to figure out how to get the 20 to be the key. Also, the OP really meant JavaScript object, not JSON object.
0

Yes, you can do it like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.