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<p.province.length;i++){
window.alert(p.province[i]);
}
</script>