18 Dec 2008 @ 9:49 AM 

JSON is really simple for those that haven’t had a chance to use it yet, maybe it’s just me but when I stumble across a new TLA or FLLA (that’s a three letter acronym or a four letters long acronym) I usually very apprehesive. But I can give you an all-you-need-to-know JSON tutorial right here.

JSON is a light, text-based XML substitute.
A JSON string is just a list of keys & values : { ‘key’ : value, ‘key’: value, ‘key’: value, … }
The value part can be either:
A string  { ‘forename’ : ‘mark’ }
An array { ’skillz’ : [ 'ruby', 'rails', 'jquery', 'linux'] }  (yeah, I’ll crack the jokes)
A hash { ‘likes’ : { ‘food’ : ‘lasagna’, ‘movie’ : ‘the thing’, ‘team’ : ‘celtic’ } }
You can also nest these so that array can contain hashes and hashes can contain arrays.

So far so good yeah? Well that’s it, that’s all you need to know about JSON.

But here is the cool bit, if you have the JSON stored in a string called json_string you can do this : var json_object = eval( ‘(’ + json_string + ‘)’ ) and then access all the values in the new json_object programmically!

Lets look at a simple example

function json_test()
{
var json_string = "{ 'astring' : 'simple string', 'ahash' : { 'key1':'value1','key2':'value2'},'anarray':['zero','one','two'] }";
var json_object = eval( '(' + json_string + ')' );
alert(json_object.astring); // outputs 'simple string'
alert(json_object.ahash.key1); //outputs 'value1'
alert(json_object.ahash['key1']); // alternative way to access a hash
alert(json_object.ahash.key2); // outputs 'value2'
alert(json_object.anarray[0]); // outputs 'zero'
alert(json_object.anarray[1]); // outputs 'one'
alert(json_object.anarray[2]); // outputs 'two'
}

This is a massively handy way of passing information to your javascript in an easy to edit form that is programmically accessible, XML originally promised the same thing but has bloated out over the years to the point where xml parsers are fairly hefty bits of code and XML has lost some of it’s human-readability. JSON gives us a quick ‘n’ dirty way to pass information between browser & server in a lightweight way.

So there is my 5 minute tutorial, it probably only took you 3 minutes so have a cup of coffee on me.

I’ll put a post up soon showing a more in-depth use of JSON and how I used it to give a web app I’m working on an extendible, flexible dynamic way to create complex forms on the fly.

Tags Tags: ,
Categories: Jquery
Posted By: admin
Last Edit: 21 Dec 2008 @ 10 30 AM

E-mailPermalinkComments (0)
\/ More Options ...
Change Theme...
  • Role »
  • Posts »
  • Comments »
Change Theme...
  • VoidVoid (Default)
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LiteLightweight