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:
- //A Simple Example:
- // Your JSON object(yourData) has a name property,
- // you could get it this way:
- var name = yourData.Name;
- // alternatively you can use a string index:
- var name = yourData["Name"];
- //A Nested Example
- // Your JSON object(yourData) has a Books object
- // with nested Book objects
- var books = yourData.Books;
- for (var x in books)
- {
- var book = books[x];
- var title = book.title;
- }
Accessing an Array type in JSON:
- //A Nested Example with an Array
- // Your JSON object(yourData) has a
- // Books array with nested Book objects
- var books = yourData.Books;
- for (var x = 0; x++; x
- <p><strong>Getting Property Names</strong></p>
- <pre name="code" class="javascript">// When you want to know the name of the
- // properties of an object you can iterate
- // through the object using for - in loop
- var books = yourData.Books;
- for (var x in books)
- {
- alert(x);
- }
- </pre>
- <!-- AddThis Button BEGIN -->
- <script type="text/javascript">
- var addthis_pub = '';
- var addthis_language = 'en';var addthis_options = 'email, favorites, digg, delicious, myspace, google, facebook, reddit, live, more';
- </script>
- <div class="addthis_container">
- <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>
- </div>
- <!-- AddThis Button END -->
Fri, Jun 26, 2009
Tech Tips