Java script: access properties of a complex JSON object

Lately I needed to dynamically access the value of a nested property in a complex JSON object in a jQuery plug-in I wrote. Since to my knowledge this is not possible directly I wrote a little function in Java Script.

var findValue = function(item, name) {
    var token = /w+/g;
    var results = name.match(token);
    var temp = item;
    for (var i = 0; i < results.length; i++)
        temp = temp[results[i]];
    return temp;
}  

First I use a regular expression to find all property names which are separated (witch are separated by a dot in my case). Then I loop over the matches and move forward in the object tree.

If I now have an object as follows

var item = {
  Id: 1,
  Name: { FirstName: "Gabriel", LastName: "Schenker" },
  ...
}

I can access the value of the LastName property with this function call

findValue(item, 'Name.FirstName')

Related Articles:

    Post Footer automatically generated by Add Post Footer Plugin for wordpress.

    About Gabriel Schenker

    Gabriel N. Schenker started his career as a physicist. Following his passion and interest in stars and the universe he chose to write his Ph.D. thesis in astrophysics. Soon after this he dedicated all his time to his second passion, writing and architecting software. Gabriel has since been working for over 12 years as an independent consultant, trainer, and mentor mainly on the .NET platform. He is currently working as chief software architect in a mid-size US company based in Austin TX providing software and services to the pharmaceutical industry as well as to many well-known hospitals and universities throughout the US and in many other countries around the world. Gabriel is passionate about software development and tries to make the life of developers easier by providing guidelines and frameworks to reduce friction in the software development process. Gabriel is married and father of four children and during his spare time likes hiking in the mountains, cooking and reading.
    This entry was posted in jQuery, plugins. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
    • Michael Hart

      I don’t get why you can’t do item.Name.FirstName?

    • Michael Hart

      And is it just me, or are the times/dates a little screwy on this blog? It says your post was “Posted Mar 10 2009, 09:56 AM”, but then my last comment was made at “03-10-2009 3:16 AM”.

      No biggie, just thought I’d point out that I pre-empted you by a good six hours :-)

      (would be great if the comment dates were not locale specific too, but now I’m just getting nitpicky)

    • http://michael.josi.de michael

      I agree with Michael Hart, item.Name.FirstName is much shorter and comes without a library or additional (global) function.

    • http://keetology.tumblr.com/ Keeto

      Michael got it right: why the need for such a function? You can easily access it via item.Name.FirstName. Or why not use square-bracket accessors if these are variable, like item['Name']['FirstName']? The function is too trivial for actual usage.

    • Nicolas

      I have to agree with Michael. If you already know what exactly you are looking for, and where it is in your JSON object then its fairly trivial stuff.

      In cases where you don’t know what exactly your looking for or how exactly your JSON object is structured, I find the function proposed here quite useful:
      http://stackoverflow.com/questions/561702/in-javascript-how-would-you-build-a-method-that-compares-value-a-with-value-b

    • http://fforw.de Sven Helmberger

      In my opinion this problem is better solved with given in a data extraction callback function instead of the string. you can just as well decentralize the knowledge about the property path needed but you don’t need your function.

    • http://colinramsay.co.uk Colin Ramsay

      Gabriel, try putting this into the Firebug console:

      var item = {
      Id: 1,
      Name: { FirstName: “Gabriel”, LastName: “Schenker” }
      };

      console.debug(item.Name.LastName);

      It will output “Schenker”. Additionally, it is not “Java script” but “JavaScript”, which is an important difference to pedants like me ;)

    • http://miscjibberish.blogspot.com Jeremy Wiebe

      Wouldn’t it be as simple as doing this:

      var result = eval(“item.Name.FirstName”);

      You may not want to do this for security purposes in some cases though.

    • http://sergiopereira.com/blog Sergio Pereira

      @Michael, Gabriel’s post mentions that he needs to do this dynamically, so the dot notation like that doesn’t help.
      @Keeto gave the suggestion I was about to give – square brackets notation.
      @Jeremy, eval isn’t something that you’s want to use all the time, especially if you don’t control the source of those strings. There’s generally a good way to avoid uses of eval with cleaner JavaScript.

    • http://colinramsay.co.uk Colin Ramsay

      I see, sorry Gabriel, I misunderstood your requirements.

    • http://www.lostechies.com/members/gnschenker/default.aspx Gabriel N. Schenker

      @all: it is indeed important to note that I needed to dynamically resolve properties. So no direct access…

    • Michael Hart

      Ah righto – sorry, my bad, I didn’t quite get that from the example.

      Can you give more context about where this expression is coming from? ie, why is it already in the format “Name.FirstName”? If it’s for an XPath type situation, then I think JSONPath already covers this (http://goessner.net/articles/JsonPath/).

      Also, I think there’s possibly a typo in the loop – I think it should be:

      temp = temp[results[i]];

    • Michael Hart

      Hmmm, interesting – maybe that’s why yours didn’t work either… there’s a hidden “i” in square brackets in there…

      Will try again:

      temp = temp[ results[ i ] ];

    • http://www.insideinfo.com.au Terry Walker

      Wow, I never knew thataccess properties of a complex JSON object. That’s pretty interesting…

    • tommaso

      hi guys, I really need your help.

      here is the problem: I have a software project in the repository but I don’t want that some people access to one or more folders/files. If I set the security on those file everithing is ok. the problem is that, when I create a Branch I have to set again the security rule to access those critical folders/files. how can I do to ensure that access rules are inherited in the branch?

      please help me!!

      thank you very much!!

      Tommaso

    • Felix Grund

      Hey Gabriel,

      I was just searching for a solution for this problem. Yours works fine, but only if I put a backslash before w+ in the regular expression:
      var token = /w+/g;Did you forget that our is it something I just can’t see at the moment?Cheer,Felix