Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery and JSON: getting an element by name

I have the following JSON:

var json = { "system" : { "world" : { "actions" : { "hello" : { "src" : "hello world/hello world.js", "command" : "helloWorld" } } } } }

I have the following javascript:

var x = "system";
// get the contents of system by doing something like json.getElementByName(x)

How do I get the contents of system using json and x in jQuery?

like image 951
Chetan Avatar asked Feb 10 '10 22:02

Chetan


3 Answers

Just use:

var x = "system";
json[x];

It is a key/value system of retrieval, and doesn't need a function call to use it.

like image 164
Doug Neiner Avatar answered Oct 07 '22 08:10

Doug Neiner


Well to my knowledge jQuery doesn't navigate arbitrary objects like that - just the DOM. You could write a little function to do it:

function findSomething(object, name) {
  if (name in object) return object[name];
  for (key in object) {
    if ((typeof (object[key])) == 'object') {
      var t = findSomething(object[key], name);
      if (t) return t;
    }
  }
  return null;
}

It should be obvious that I haven't put that function through an elaborate QA process.

like image 28
Pointy Avatar answered Oct 07 '22 09:10

Pointy


Try using JSON Path, it is like XPath expression.

like image 1
Muhammad Soliman Avatar answered Oct 07 '22 09:10

Muhammad Soliman