6

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?

Chetan
  • 46,743
  • 31
  • 106
  • 145

3 Answers3

12

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.

Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
  • 1
    Yes that works unless the label corresponding to the value of "x" is buried deep in the jungle of substructure dangling off the "json" object. – Pointy Feb 10 '10 at 22:07
  • Perhaps a better example of what you need is `x = "hello"` ? You might want to update your question to reflect that. – Doug Neiner Feb 10 '10 at 22:08
4

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Should check for null on 'object' ... `if (object[key] && (typeof (object[key])) == 'object' )` ... – lyolikaa Aug 20 '20 at 15:23
1

Try using JSON Path, it is like XPath expression.

Simon Arnold
  • 15,849
  • 7
  • 67
  • 85
Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75