Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New Coder
    Join Date
    Aug 2012
    Posts
    37
    Thanks
    5
    Thanked 0 Times in 0 Posts

    How to get variable value in JSON by using Javascript

    I have converted my .xml code to .json

    For xml I am using something like this:

    Code:
    var stage = xml.getElementsByTagName("stage" + game.current_stage)[0];
    How can you do that in json? I want something like this:

    Code:
    var stage = json."stage"+ game.current_stage;
    and how can I set this JSON code in an variable:
    Code:
    {
      "stage_startposition" : [ 
         {"x":0}, 
         {"y":0} 
       ]
    }
    Last edited by mrbean; 11-21-2012 at 04:19 PM.

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    Code:
    var stage = json["stage"+game.current_stage];

  • #3
    New Coder
    Join Date
    Aug 2012
    Posts
    37
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by mrbean View Post
    and how can I set this JSON code in an variable:
    Code:
    {
      "stage_startposition" : [ 
         {"x":0}, 
         {"y":0} 
       ]
    }
    How can I convert the above code in javascript?

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    JSON is already valid javascript code. If you want to assign it to a variable you can just do it.
    Code:
    var myvar = {
      "stage_startposition" : [ 
         {"x":0}, 
         {"y":0} 
       ]
    }
    // access to x
    var theX = myvar.stage_startposition[0].x;
    // theX will be 0

  • #5
    New Coder
    Join Date
    Aug 2012
    Posts
    37
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Thanks!
    Is it required to use "[]" if I have multiple objects in an var?

  • #6
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    No, as long as you always have pairs of key/values and each key is unique you can replace the [] with {}
    Code:
    var myvar = {
      "stage_startposition" : { 
         "x":0, 
         "y":0 
       }
    }
    // access to x
    var theX = myvar.stage_startposition.x;
    // theX will be 0

  • Users who have thanked devnull69 for this post:

    mrbean (11-21-2012)

  • #7
    New Coder
    Join Date
    Aug 2012
    Posts
    37
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Thank youu again!
    I am quite new to json but I will work it out


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •