...

View Full Version : Resolved How to get variable value in JSON by using Javascript



mrbean
11-21-2012, 01:42 PM
I have converted my .xml code to .json

For xml I am using something like this:


var stage = xml.getElementsByTagName("stage" + game.current_stage)[0];

How can you do that in json? I want something like this:


var stage = json."stage"+ game.current_stage;

and how can I set this JSON code in an variable:

{
"stage_startposition" : [
{"x":0},
{"y":0}
]
}

devnull69
11-21-2012, 01:45 PM
var stage = json["stage"+game.current_stage];

mrbean
11-21-2012, 03:44 PM
and how can I set this JSON code in an variable:

{
"stage_startposition" : [
{"x":0},
{"y":0}
]
}

How can I convert the above code in javascript?

devnull69
11-21-2012, 04:02 PM
JSON is already valid javascript code. If you want to assign it to a variable you can just do it.


var myvar = {
"stage_startposition" : [
{"x":0},
{"y":0}
]
}
// access to x
var theX = myvar.stage_startposition[0].x;
// theX will be 0

mrbean
11-21-2012, 04:18 PM
Thanks!
Is it required to use "[]" if I have multiple objects in an var?

devnull69
11-21-2012, 07:45 PM
No, as long as you always have pairs of key/values and each key is unique you can replace the [] with {}


var myvar = {
"stage_startposition" : {
"x":0,
"y":0
}
}
// access to x
var theX = myvar.stage_startposition.x;
// theX will be 0

mrbean
11-21-2012, 08:53 PM
Thank youu again!
I am quite new to json but I will work it out



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum