SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    This is my JSON but I can't access part of it

    This is a sample of the result after running data=JSON.parse(response) on a value returned by my server (PHP script).

    {"value_1":0,"value_2":["a","b"]}

    I can get the 'value_1' value by using data.value_1 but I just can't get the 'value_2' value. It looks like an array so surely data.value_2 gets the array and then I go form there, but it doesn't work.

    Am I doing something wrong?

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,039
    Mentioned
    152 Post(s)
    Tagged
    2 Thread(s)
    When I try this is in the javascript console in chrome I can get data.value_1 and data.value_2 no problem.

    Code:
    > JSON.parse('{"value_1":0,"value_2":["a","b"]}')
    Object
      value_1: 0
      value_2: Array[2]
        0: "a"
        1: "b"
        length: 2
    Rémon - Hosting Advisor

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  3. #3
    SitePoint Wizard bronze trophy Immerse's Avatar
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    1,661
    Mentioned
    7 Post(s)
    Tagged
    1 Thread(s)
    Have you tried data.value_2.0 and data.value_2.1 ?

  4. #4
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,039
    Mentioned
    152 Post(s)
    Tagged
    2 Thread(s)
    Quote Originally Posted by Immerse View Post
    Have you tried data.value_2.0 and data.value_2.1 ?
    I hope not, because that won't work

    Quote Originally Posted by Chrome javascript console
    SyntaxError: Unexpected number
    Instead of data.value_2.0 and data.value_2.1 you should use data.value_2[0] and data.value_2[1] since data.value_2 is an array, not an object.

    You can access an object like it is an array (in this case, data['value_1'] and data['value_2'] both work), but not the other way around.
    Rémon - Hosting Advisor

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  5. #5
    SitePoint Wizard bronze trophy Immerse's Avatar
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    1,661
    Mentioned
    7 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by ScallioXTX View Post
    I hope not, because that won't work
    Ah, eh... trick question


Bookmarks

Posting Permissions

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