Friday, March 13, 2015

Array in JSON

While defining array in JSON it has some protocols, they are enclosed with square brackets and the vales inside an array are separated by comma, unlike other indexing of an array can start form 0 or 1 here. JSON array is well ordered sequence of values.

Protocol for declaring an array in JSON:

  • An array must be wrapped in square brackets, i.e. “[“in starting and “]” at end of an array.
  • Commas”,” must be used to separate the values.
  • Indexing in an array can start with 0 or 1.
  • If the key names are sequential integers array must be used.
Syntax:

 [ value1, value2,.......,value n]  


Example:

HTML Document (array.html)
 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
 <meta charset="UTF-8">  
 <title>json</title>  
 </head>  
 <body>  
 <h2>Example of JSON Array</h2>  
 <p id="content"></p>  
 <p id="content1"></p>  
 <script>  
 var info = '{"courses":[' +  
       '{"title":"HTML","description":"HyperText Markup Language" },' +  
       '{"title":"CSS","description":"Cascading Style Sheet" },' +  
       '{"title":"JSON","description":"JavaScript Object Notation" }]}';  
 obj = JSON.parse(info);  
 document.getElementById("content").innerHTML =  
       "Title: " + obj.courses[0].title + ": " + "<br/> Description: " + obj.courses[0].description;  
 obj = JSON.parse(info);  
 document.getElementById("content1").innerHTML =  
       "Title: " + obj.courses[2].title + ": " + "<br/> Description: " + obj.courses[2].description;  
 </script>  
 </body>  
 </html>

No comments:

Post a Comment