js中的json對象

來源:互聯網
上載者:User

js中的json對象
1.JSON(JavaScript Object Notation)一種簡單的資料格式,比xml更輕巧。JSON是JavaScript原生格式,這意味著在JavaScript中處理JSON資料不需要任何特殊的API或工具包。
JSON的規則很簡單:對象是一個無序的“‘名稱:值’對”集合。一個對象以“{”(左括弧)開始,“}”(右括弧)結束。每個“名稱”後跟一個“:”(冒號);“‘名稱/值’對”之間使用“,”(逗號)分隔。
規則如下:
1)映射用冒號(“:”)表示。名稱:值
2)並列的資料之間用逗號(“,”)分隔。名稱1:值1,名稱2:值2
3) 映射的集合(對象)用大括弧(“{}”)表示。{名稱1:值1,名稱2:值2}
4) 並列資料的集合(數組)用方括弧(“[]”)表示。
[
{名稱1:值,名稱2:值2},

{名稱1:值,名稱2:值2}

]
5 )元素值可具有的類型:string, number, object, array, true, false, null

2.json中的五種寫法:

1)傳統方式儲存資料,調用資料

<script type="text/javascript">  //JS傳統方式下定義"類"  function Person(id,name,age){  this.id = id;  this.name = name;  this.age = age;  }  //JS傳統方式下建立"對象"  var p = new Person(20141028,"一葉扁舟",22);    //調用類中的屬性,顯示該Person的資訊  window.alert(p.id);  window.alert(p.name);  window.alert(p.age);  </script>

2)第一種樣式:
 <script type="text/javascript">   var person = {    id:001,    name:"一葉扁舟",    age:23   }   window.alert("編號:"+person.id);   window.alert("使用者名稱:"+person.name);   window.alert("年齡:"+person.age);   </script>


3)第二種樣式:

<script type="text/javascript">var p = [{id:001,name:"一葉扁舟",age:22},{id:002,name:"無悔",age:23},{id:003,name:"無悔_一葉扁舟",age:24}];      for(var i = 0; i < p.length; i++){     window.alert("編號:"+p[i].id);     window.alert("使用者名稱:"+p[i].name);     window.alert("年齡:"+p[i].age);      }   </script>

4)第三種樣式:
  <script type="text/javascript">var p = {"province":[{"city":"福州"},{"city":"廈門"},{"city":"莆田"}]};window.alert("所在城市:" + p.province[0].city);  </script>

5)第四種樣式:
<script type="text/javascript">var p = {   "ids":[{"id":001},{"id":002},{"id":003}],  "names":[{"name":"一葉扁舟"},{"name":"無悔"},{"name":"無悔_一葉扁舟"}]};     for(var i = 0; i < p.names.length; i++){     window.alert("名字:"+p.names[i].name);   }    for(var i = 0; i < p.ids.length; i++){    window.alert("id:"+p.ids[i].id);    }       </script>

6)第五種樣式:

<script type="text/javascript">var p = {"province":["福州","廈門","莆田"]};window.alert("城市的個數:"+p.province.length);window.alert("分別是:\n");for(var i=0;i


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.