Basic JSON Parsing
HTML
<button id="Go">Go</button>
JavaScript
document.getElementById("Go").onclick = function()
{
//we want to parse this json into a javascript object
var jsonstring = '[ { "name": "A", "value": "1" }, { "name": "B", "value": "2" }]';
//lazy way is to use eval
var o1 = eval(jsonstring);
alert(o1[0].name);
//parse json in a safe way with native javascript
var o3 = JSON.parse(jsonstring);
alert(o3[1].name);
//note that the native parser does not fall for the bad code and throws an exception
try
{
var o4 = JSON.parse(notJSONButYouEvalItAnyway);
}
catch(e)
{
alert(e);
}
//you can also parse json with jquery
var o5 = jQuery.parseJSON(jsonstring);
alert(o5[0].value);
};