這次帶給大家JS內JSON物件定義和取值實例步驟詳解,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)傳統方式儲存數據,調用資料
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <script type= "text/javascript" >
function Person(id,name,age){
this.id = id;
this.name = name;
this.age = age;
}
var p = new Person(20141028, "一叶扁舟" ,22);
window.alert(p.id);
window.alert(p.name);
window.alert(p.age);
</script>
|
登入後複製
2)第一種樣式:
1 2 3 4 5 6 7 8 9 10 | <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)第二種樣式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <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)第三種樣式:
1 2 3 4 5 6 7 8 9 10 | <script type= "text/javascript" >
var p = {
"province" :[
{ "city" : "福州" },
{ "city" : "厦门" },
{ "city" : "莆田" }
]
};
window.alert( "所在城市:" + p.province[0].city);
</script>
|
登入後複製
5)第四種樣式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <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)第五種樣式:
1 2 3 4 5 6 7 8 9 10 | <script type= "text/javascript" >
var p = {
"province" :[ "福州" , "厦门" , "莆田" ]
};
window.alert( "城市的个数:" +p.province.length);
window.alert( "分别是:\n" );
for ( var i=0;i<p.province.length;i++){
window.alert(p.province[i]);
}
</script>
|
登入後複製
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
JS Promise使用案例解析
#jQuery實作模糊查詢實戰案例解析
#
以上是JS內JSON物件定義與取值實例步驟詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!