INTRODUCTION

A JSON Array is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values. A JSON Object is an unordered collection of name/value pairs.

Simple Array Objects Syntax

JSON objects can be created with JavaScript.

Let us see the various ways of creating JSON objects using JavaScript.

  • Creation of an empty Object
    var JSONOb = {};
  • Creation of a new Object
    var JSONOb = new Object();

  • Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attribute is accessed by using '.' Operator,
    var JSONObj = {"bookname":"VB BLACK BOOK", "price":500};

Example for JSON Array Object run in HTML

  1. <html>
  2. <head>
  3. <title>Creation of array object in javascript using JSON</title>
  4. <script language = "javascript" >
  5. document.writeln("<h2>JSON array object</h2>");
  6. var books = { "Java" : [
  7. { "Name" : "Core Java", "price" : 600 },
  8. { "Name" : "Guide to Java", "price" : 400 }],
  9. "JSP" : [
  10. { "Name" : "Basics of JSP", "price" : 1000 },
  11. { "Name" : "Tutorial of JSP", "price" : 1300 }]
  12. }
  13. var i = 0
  14. document.writeln("<table border = '2'><tr>");
  15. for(i = 0;i<books.Java.length;i++){
  16. document.writeln("<td>");
  17. document.writeln("<table border = '1' width = 100 >");
  18. document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Java[i].Name+"</td></tr>");
  19. document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Java[i].price +"</td></tr>");
  20. document.writeln("</table>");
  21. document.writeln("</td>");
  22. }
  23. for(i = 0;i<books.JSP.length;i++){
  24. document.writeln("<td>");
  25. document.writeln("<table border = '1' width = 100 >");
  26. document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.JSP[i].Name+"</td></tr>");
  27. document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.JSP[i].price+"</td></tr>");
  28. document.writeln("</table>");
  29. document.writeln("</td>");
  30. }
  31. document.writeln("</tr></table>");
  32. </script>
  33. </head>
  34. <body>
  35. </body>
  36. </html>
Output


Result

Thus, we have successfully learned the JSON Array object creation program.