LearningAPI has moved to a new blog!

The learningapi blog has moved to a new URL. These posts will remain here, but all new content has moved to learningAPI.com: Digital Media, Streaming Video & Educational Technology. You may also subscrdibe to the RSS feed for the new learningAPI.com blog.

November 09, 2005

JSON - Simple, Elegant Data Structures for Javascript/AJAX

I've used this technique recently to develop a project that uses client-side Javascript to handle all of its data and business logic. I didn't know, until reading about it on Anil Dash's excellent treatise on "technologies and techniques are going to be popular in the coming months and into the next year", that this technique had a name.  JSON (JavaScript Object Notation) is an incredibly useful technique for building simple, powerful data structures into Javascript programs.  In this day of AJAX and other powerful ways to build outstanding interfaces and applications using client-side code, JSON is more useful than ever.

In a nutshell, you can define a data object explicitly like this:

var myData = {
    "title" : "In the Bubble: Designing in a Complex World",
    "author" : "John Thackara",
    "chapters" : [
         { "name" : "Lightness", "length" : "32", "finished" : true },
         { "name" : "Speed", "length" : "23", "finished" : true },
         { "name" : "Mobility", "length" : "41", "finished" : false }
         ]
    }

Then, you can access these in your Javascript code like you would an associative array:

myData.title evaluates to
"In the Bubble: Designing in a Complex World"
myData.chapters[0].name evaluates to "Lightness"
or assign var chaps = myData.chapters; and then do chaps[1].length to get "23"

If your data comes to you as a String, you can convert it to a JSON object  with 
var myObject = eval('(' + aJSONtext + ')');

Posted by larryb at 05:44 AM [permanent link]
Category: Web and Software Development
TrackBack URL for this entry:
http://www.learningapi.com/cgi-bin/mt-tb.cgi/71

Listed below are links to weblogs that reference 'JSON - Simple, Elegant Data Structures for Javascript/AJAX' from learningAPI.com: Media and Learning Technology - Larry Bouthillier.