jQuery and JSON: getting an element by name
Asked Answered
C

3

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?

Chintzy answered 10/2, 2010 at 22:1 Comment(0)
C
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.

Crystie answered 10/2, 2010 at 22:6 Comment(2)
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.Tarttan
Perhaps a better example of what you need is x = "hello" ? You might want to update your question to reflect that.Crystie
T
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.

Tarttan answered 10/2, 2010 at 22:5 Comment(1)
Should check for null on 'object' ... if (object[key] && (typeof (object[key])) == 'object' ) ...Fusibility
R
1

Try using JSON Path, it is like XPath expression.

Rubricate answered 16/6, 2012 at 19:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.