2 Replies - 1396 Views - Last Post: 13 March 2012 - 11:24 AM

#1 ammuhere  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 01-April 10

how to access JSON object using variable?

Posted 09 March 2012 - 08:07 PM

i have a json object as follows

var data={
    "name": "DIV",
    "id": 1,
    "child": [
        {
            "name": "DIV",
            "id": "1.1"
        }
    ]
}


if i have a value in a variable like this

var i="child[0]"

how can i access the specified object from the json object data??
i tried data[eval(i)]. But it return child undefined.
How to access the object using variable?

This post has been edited by JackOfAllTrades: 10 March 2012 - 04:23 AM
Reason for edit:: Added code tags


Is This A Good Question/Topic? 0
  • +

Replies To: how to access JSON object using variable?

#2 chinchang  Icon User is offline

  • Indie Game Developer
  • member icon

Reputation: 192
  • View blog
  • Posts: 725
  • Joined: 22-December 08

Re: how to access JSON object using variable?

Posted 10 March 2012 - 02:11 AM

You'll have to process the variable i a little bit before you can actually use it. This exploits the fact that objects can be used as associative arrays.

You can do something like:
// get a word followed by some number
var parts = i.match(/^(\w+)\[(\d+)/)


Now you will have the property name and the index in the parts array using which you can simply do:

answer = data[parts[1]];
if(parts[2]) answer = answer[parseInt(parts[2],10)];


Read more about regex here.
Was This Post Helpful? 0
  • +
  • -

#3 BobRodes  Icon User is offline

  • Your Friendly Local Curmudgeon
  • member icon

Reputation: 574
  • View blog
  • Posts: 2,989
  • Joined: 19-May 09

Re: how to access JSON object using variable?

Posted 13 March 2012 - 11:24 AM

You just haven't specified your variable properly. With your json object, you have one object called data (not an array,because you don't have a [ there), with an array of child objects (because of the [) called child, in which you have one element. So, data.child[0].name will evaluate to "DIV" as you seem to want.

So, you probably want var i = data.child[0] instead of what you have. Then i.name will evaluate to "DIV" as well.

"child" is undefined in your example because you don't specify it as a child of data, although you have defined it that way. That makes it a different "child" from "data.child".

See? :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1