//20.1 语法
//JAVASCRIPT 是对JSON数据支持的。
//JSON 可以申明三种类型的值 简单值("hello world") 对象({"name":"maosi"}) 数组(["a","b","c"]) //20.1.2 json对象 var person = { "name": "Nicholas", "age": 29 };
person = {
"name": "Nicholas",
"age": 29,
"school": {
"name": "Merrimack College",
"location": "North Andover,MA"
}
}
//js 对象
var person = { name: "Nicholas", age: 29 }; //20.1.3 数组(js语法与json 数组一样)
var values = [25, 'hi', true];
//复杂结构数组
[
{
"title": "Professnional javascript",
"authors": [
"Nicholas C Zakas"
],
edition: 3,
year: 2011
},
{
"title": "Professnional javascript",
"authors": [
"Nicholas C Zakas"
],
edition: 2,
year: 2009
}
] //20.2 解析与序列化 //序列化
var book = {
title: "professional JavaScript",
authors: ["Nicholas C Zakas"],
edition: 3,
year: 2011,
releaseDate:new Date(2011,1,1);
};
var jsontext = JSON.stringify(book); //20.2.2 序列化选项 jsontext = JSON.stringify(book, ["title", "edition"]); //表示序列化的属性数组(指定只序列化哪些属性)
//序列化属性进行逻辑处理
jsontext = JSON.stringify(book, function (key, value){
switch (key) {
case "authors":
return value.JSON(',');
case "year":
return 5000;
case "edition":
return undefined; //此处被定义为undefined后字符串后序列化时会忽略该字段,ignore
default:
return value;
} }); //JSON字符串缩进,上述方法会把JSON序列化成一行长长的字符串
jsontext = JSON.stringify(book,null,4); //第三个参数表示每个级别缩进的空格数 JSON.parse(jsontext,function(key,value){
if(key =='releaseDate'){
return new Date(value); //特定对象要进行字符串还原操作
}
else{
return value;
}
}); //20.3 小结