Friday, August 11, 2006

AJAX without XML

JSON is Java Script Object Notation, a lightweight data interchange format over the internet and is language independent.

But Why we need JSON when we have XML, the biggest issue with the XML is its parsing . while JSON is easy to parse and it gives us object which are easy to maintain and manipulate.

JSON contains:

Objects with comma seperated Key/Value pair,
Arrays with comma seperated Value.

=> Value can be String, Number, Char, Int, Exp, or an Object, Array, e.t.c.


Sample
XML


{breakfast-menu}
{food}
{name}Belgian Waffles{/name}
{price}$5.95{/price}
{description}two of our famous Belgian Waffles with plenty of real maple syrup {/description}
{calories}650{/calories}
{/food}

{food}
{name}Strawberry Belgian Waffles{/name}
{price}$7.95{/price}
{description}light Belgian waffles covered with strawberrys and whipped cream{/description}
{calories}900{/calories}
{/food}

{/BREAKFAST-MENU}


JSON

{"breakfast-menu":
{ "food":[
{"name": "Belgian Waffles",
"price": "5.95", "description":
"two of our famous Belgian Waffles with ...", "calories": "650"
},
{"name": "Strawberry Belgian Waffles",
"price": "7.95", "description": "light Belgian waffles covered with ...",
"calories": "900" }
]
}
}

Javascript

// XMLHttpRequest completion

function var myOnComplete = function(responseText, responseXML)

{
eval(responseText);
for (var i=0; i < breakfastMenu.length; i++){
document.write(breakfastMenu[i].name + "
");
}
}

See more details on the JSON @ http://www.json.org/

So now the AJAX which uses XML as a messaging language can also use JSON which is more lighter as compared to XML parsing.