Powered By Blogger

Sunday, December 4, 2011

JSON Notes

JSON is abbreviation of Javascript Object and Array Notation
=======================
create an array in Javascript:
var myArray = new Array("Taipei", "Taichung", "Tainan");
or
var myArray = ["Taipei", "Taichung", "Tainan"];
Javascript array can be a mixed array which contains any type of object, string , number or customized object.
create an object in Javascript:
var myDog = new Object( );
myDog.name = "Allen";
myDog.age = 5;
myDog.color = "blue";
=======================
or
var myCat = {
   "name":"Allen";
   "age":5;
   "color":"blue";
}
=======================
a mixed use of array and object
var myDogs = [ {
   "name":"Allen";
   "age":5;
   "color":"blue"; },{
   "name":"Ben";
   "age":6;
   "color":"red";} ];
alert(myDogs[0].name);
alert(myDogs[1].age);
=======================
Example of JSON
var json = '{"myCats": [ {"name": "Hero", "age": 5, "color": "silver" }, {"name": "Euro", "age": 2, "color": ["brown", "white", "black"] }]}';
var obj = eval ("(" + json + ")"); 
alert('I have ' + obj.myCats.length + ' cats.'); 
alert(obj.myCats[0].name); 
alert(obj.myCats[1].name);
But eval( ) is dangerous for XSS attack so we use parser instead.
var obj = JSON.parse(json); 
alert('I have ' + obj.myCats.length + ' cats.'); 
alert(obj.myCats[0].name);
alert(obj.myCats[1].name);
=======================
Here is the way transfer an object to JSON string.
<script type="text/javascript" src="http://www.json.org/json.js"></script> 
<script type="text/javascript">
 var obj = new Object(); 
obj.myCats = new Array(new Object(), new Object()); 
obj.myCats[0].name = "Hero"; 
obj.myCats[0].age = 5; 
obj.myCats[0].color = "silver"; 
obj.myCats[1].name = "Euro"; 
obj.myCats[1].age = 2; 
obj.myCats[1].color = ["black", "white", "brown"]; 
alert(JSON.stringify (obj)); 
</script>

























No comments:

Post a Comment