{
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
}
对于 AJAX 应用程序来说,JSON 比 XML 更快更易使用:
JSON 数据的书写格式是:名称/值对。
名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值:
"firstName" : "John"
/* 基本格式 */
var person = {"name":"cat","age":11}
var name11 = person.name;
var name12 = person["name"];
/* 嵌套格式 */
// JSON { JSON,JASON }
var persons = {
"personCat": {"name":"cat","age":11},
"personDog":{"name":"dog","age":12},
"personRat":{"name":"rat","age":13}}
var personCat = persons.personCat;
var name2 = persons.personCat.name;
// Array [JSON,JASON]
var array = [
{"name":"cat","age":11},
{"name":"dog","age":12},
{"name":"rat","age":13}]
var name3 = array[0].name;
// JSON { Array[JSON,JASON], Array[JSON,JASON] }
var persons = {
"person1":[
{"name":"cat","age":11},
{"name":"dog","age":12},
{"name":"rat","age":13},],
"person2":[
{"name":"cat","age":11},
{"name":"dog","age":12},
{"name":"rat","age":13},]
}
var name4 = persons.person1[0].name;
/* 基本格式 */
var person = {"name":"cat","age":11}
for (var key in person) {
// * key默认为字符串
alert(key);
alert(person.key); // * person."name"; 无法获取
alert(person[key]); // * person["name"]; 无法获取
}
/* 嵌套格式 */
var array = [
{"name":"cat","age":11},
{"name":"dog","age":12},
{"name":"rat","age":13}]
for (var i =0;i<array.length;i++) {
var p = array[i];
for (var key in p) {
alert(key);
alert(p[key]);
}
}