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++; xGetting Property Names
// 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); }
Fri, Jun 26, 2009
Tech Tips