I saw many questions in Stackoverflow but i didn't find what exactly responds to my query.
I need to add an element to my json object:
var JSONObject = {
"shape0": {
"id": "id0",
"x1": 0,
"x2": 0,
"y1": 0,
"y2": 0
},
"shape1": {
"id": "id1",
"x1": 2,
"x2": 2,
"y1": 2,
"y2": 2
}
};
I used this syntax but in vain:
var newShape = "shape2";
JSONObject.newShape.id = "id2";
NOTE: The first thing, is that a json object? Any help will be appreciated
-
this uses arrays not json object, isn't it?user1807367– user180736706/18/2013 15:06:20Commented Jun 18, 2013 at 15:06
-
Java has nothing to do with Javascript. Tag removed.Brian Roach– Brian Roach06/18/2013 15:08:48Commented Jun 18, 2013 at 15:08
-
1What you are doing makes no sense.Dave Lawrence– Dave Lawrence06/18/2013 15:09:26Commented Jun 18, 2013 at 15:09
-
This is not a JSON object. It's a JavaScript object.Joe– Joe06/18/2013 15:09:37Commented Jun 18, 2013 at 15:09
-
@Joe : could you plz give me the right JSON objectuser1807367– user180736706/18/2013 15:12:12Commented Jun 18, 2013 at 15:12
2 Answers 2
Assuming you want to build a similar structure as the rest:
JSONObject.shape2 = {
id: 'id2',
"x1": 4,
"x2": 4,
"y1": 4,
"y2": 8
};
Or:
var shapeName = 'shape2';
JSONObject[shapeName] = {
...
};
Btw, these are not JSON objects; they are just objects, in JavaScript.
Update
The following wouldn't work:
var newShape = "shape2";
JSONObject.newShape.id = "id2";
First of all, the notation is wrong; you need to use [newShape]
. But that's not the main reason; it doesn't work because you can't dereference an object that doesn't exist yet.
JSONObject[newShape]
This will be undefined, so this:
JSONObject[newShape].id
Will result in an error TypeError: Cannot set property 'id' of undefined
-
i want to make it json object, how?user1807367– user180736706/18/2013 15:13:55Commented Jun 18, 2013 at 15:13
-
1+1 for the correct answer. Sadly, I don't think it's going to help.Brian Roach– Brian Roach06/18/2013 15:14:17Commented Jun 18, 2013 at 15:14
-
JSON stands for Javascript Object Notation meaning you are writing plain Javascript. JSON === javascript objectPinoniq– Pinoniq06/18/2013 15:15:26Commented Jun 18, 2013 at 15:15
-
@Pinoniq Not sure if you're agreeing with me or not; but yeah, JSON is just a notation; it's not plain JavaScript though, because keys must be quoted in JSON.Ja͢ck– Ja͢ck06/18/2013 15:19:18Commented Jun 18, 2013 at 15:19
-
@abualbara It's an object, just like what you have.Ja͢ck– Ja͢ck06/18/2013 15:19:49Commented Jun 18, 2013 at 15:19
You need:
var newShape="shape2";
JSONObject[newShape].id = "blar";
-
then, i can use that: JSONObject.shape2.id ?user1807367– user180736706/18/2013 15:08:47Commented Jun 18, 2013 at 15:08