Navigating a JSON object in Javascript

Fri, Jun 26, 2009

Tech Tips

The Scenario:
You are working with a web service that returns JSON. You’ve used your javascript library to convert the string into a JSON object. Now you need to access the data in the object using javascript. Here are some examples:

JSON Property Types
The properties of a JSON object are going to be of the following types: another Object or an Array of Objects. Objects are name – value pairs. The value that is returned can be a string, a number, another object, an array, true, false, or null.

Accessing an Object type in JSON:

  1. //A Simple Example:  
  2. // Your JSON object(yourData) has a name property,   
  3. //  you could get it this way:  
  4. var name = yourData.Name;  
  5. // alternatively you can use a string index:  
  6. var name = yourData["Name"];  
  7.   
  8. //A Nested Example  
  9. // Your JSON object(yourData) has a Books object   
  10. //  with nested Book objects  
  11. var books = yourData.Books;  
  12. for (var x in books)   
  13. {  
  14.  var book = books[x];  
  15.  var title = book.title;  
  16. }  

Accessing an Array type in JSON:

  1. //A Nested Example with an Array  
  2. // Your JSON object(yourData) has a   
  3. // Books array with nested Book objects  
  4. var books = yourData.Books;  
  5. for (var x = 0; x++; x  
  6. <p><strong>Getting Property Names</strong></p>  
  7. <pre name="code" class="javascript">// When you want to know the name of the   
  8. //  properties of an object you can iterate   
  9. //  through the object using for - in loop  
  10. var books = yourData.Books;  
  11. for (var x in books)   
  12. {  
  13.  alert(x);  
  14. }  
  15. </pre>  
  16.   
  17. <!-- AddThis Button BEGIN -->  
  18. <script type="text/javascript">  
  19. var addthis_pub = '';  
  20. var addthis_language = 'en';var addthis_options = 'email, favorites, digg, delicious, myspace, google, facebook, reddit, live, more';  
  21. </script>  
  22. <div class="addthis_container">  
  23. <a href="http://www.addthis.com/bookmark.php?v=20" onmouseover="return addthis_open(this, '', 'http%3A%2F%2Fwww.pressthered.com%2Fnavigating_a_json_object_in_javascript%2F', 'Navigating+a+JSON+object+in+Javascript')" onmouseout="addthis_close()" onclick="return addthis_sendto()"><img src="https://s7.addthis.com/static/btn/lg-share-en.gif" width="125" height="16" border="0" alt="Bookmark and Share"></a><script type="text/javascript" src="https://s7.addthis.com/js/200/addthis_widget.js"></script>  
  24. </div>  
  25. <!-- AddThis Button END -->                       
  26.                       
,

Comments are closed.