Sunday, October 7, 2012

Javascripy: simple encode/decode Json LIbrary

Use the Extjs JSON library

// create new object
var myObject = new Object();
// set properties to the object
myObject["RB"] = "(aBc+ABC)";
myObject["RA"] = "(aBC+AbC)";
myObject["SA"] = "(abc+ABc)";
myObject["SB"] = "(abC+Abc)";
//from javascript object to json text:
var myJsonString = Ext.JSON.encode(myObject);


//from jsontext to javascript object
var myResponseString = '{"RB":"(aBc+ABC)","RA":"(aBC+AbC)","SA":"(abc+ABc)","SB":"(abC+Abc)"}';
var myResponseObject = Ext.JSON.decode(myResponseString);
alert(myResponseObject["RB"]) // "(aBc+ABC)"
alert(myResponseObject["RA"]) // "(aBC+AbC)"
alert(myResponseObject["SA"]) //  "(abc+ABc)"
alert(myResponseObject["SB"]) //  "(abC+Abc)"

Resources:
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.JSON
http://www.sencha.com/forum/showthread.php?3333-json-encode-decode

No comments: