鍍金池/ 教程/ Java/ JSON 對象(Object)
JSON 語法
JSON 概述
Json教程
JSON 與XML比較
JSON 數(shù)據(jù)類型
JSON & Python
JSON & Perl
JSON & Ajax
JSON & PHP
JSON 教程首頁
JSON & Java
JSON 對象(Object)
JSON & Ruby
JSON 框架模式(Schema)

JSON 對象(Object)

創(chuàng)建簡單對象

JSON 對象,可以使用Javascript 創(chuàng)建。讓我們來看看各種方式使用 Javascript創(chuàng)建JSON對象:

  • 創(chuàng)建一個空的對象:

var JSONObj = {};
  • 創(chuàng)建新的對象:

var JSONObj = new Object();
  • 創(chuàng)建一個對象和屬性bookname 字符串,屬性數(shù)值 price 的值。訪問屬性通過使用 '.' 操作符:

var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };

這是一個例子,它顯示了創(chuàng)建一個對象在 javascript 中使用JSON,下面的代碼保存為 json_object.htm :

<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language="javascript" >

  var JSONObj = { "name" : "yiibai.com", "year"  : 2005 };
  document.write("<h1>JSON with JavaScript example</h1>");
  document.write("<br>");
  document.write("<h3>Website Name="+JSONObj.name+"</h3>");  
  document.write("<h3>Year="+JSONObj.year+"</h3>");  

</script>
</head>
<body>
</body>
</html>

現(xiàn)在,讓我們嘗試打開 json_object.htm 使用IE或其他任何支持 JavaScript 的瀏覽器,這將產(chǎn)生以下結(jié)果:

json objects

創(chuàng)建數(shù)組對象

下面的例子顯示了如何創(chuàng)建一個數(shù)組對象在javascript 中使用JSON中,保存下面的代碼 asjson_array_object.htm:

<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language="javascript" >

document.writeln("<h2>JSON array object</h2>");

var books = { "Pascal" : [ 
      { "Name"  : "Pascal Made Simple", "price" : 700 },
      { "Name"  : "Guide to Pascal", "price" : 400 }
   ],                       
   "Scala"  : [
      { "Name"  : "Scala for the Impatient", "price" : 1000 }, 
      { "Name"  : "Scala in Depth", "price" : 1300 }
   ]    
}    

var i = 0
document.writeln("<table border='2'><tr>");
for(i=0;i<books.Pascal.length;i++)
{	
   document.writeln("<td>");
   document.writeln("<table border='1' width=100 >");
   document.writeln("<tr><td><b>Name</b></td><td width=50>"
   + books.Pascal[i].Name+"</td></tr>");
   document.writeln("<tr><td><b>Price</b></td><td width=50>"
   + books.Pascal[i].price +"</td></tr>");
   document.writeln("</table>");
   document.writeln("</td>");
}

for(i=0;i<books.Scala.length;i++)
{
   document.writeln("<td>");
   document.writeln("<table border='1' width=100 >");
   document.writeln("<tr><td><b>Name</b></td><td width=50>"
   + books.Scala[i].Name+"</td></tr>");
   document.writeln("<tr><td><b>Price</b></td><td width=50>"
   + books.Scala[i上一篇:JSON 教程首頁下一篇:JSON 數(shù)據(jù)類型