二十.JSON

JSON 中的对象要求给属性加引号
books[2].title 等同于 doc.getElementsByTagName("book")[2].getAttribute("title")

20.1 序列化选项

1.JSON.stringify(数据,数组或者函数表示要显示的属性,控制结果中的缩进和空白符)

//JSON.stringify()的第二个参数是一个数组,其中包含两个字符串:title和edition
//这两个属性与将要序列化的对象中的属性是对应的,因此在返回的结果字符串中,就只会包含这两个属性:{"title":"Professional JavaScript","edition":3}

var book = { 
 "title": "Professional JavaScript", 
 "authors": [ 
 "Nicholas C. Zakas" 
 ], 
 edition: 3, 
 year: 2011 
 }; 
var jsonText = JSON.stringify(book, ["title", "edition"]); 

//如果第二个参数是函数,如果函数返回了undefined,那么相应的属性会被忽略
//{"title":"Professional JavaScript","authors":"Nicholas C. Zakas","year":5000} 
var book = { 
 "title": "Professional JavaScript", 
 "authors": [ 
 "Nicholas C. Zakas" 
 ], 
 edition: 3, 
 year: 2011 
 }; 
var jsonText = JSON.stringify(book, function(key, value){ 
  switch(key){ 
 case "authors": 
 return value.join(",") 
 case "year": 
 return 5000; 
 case "edition": 
 return undefined; 
 default: 
 return value; 
 } 
}); 

//第三个参数用于控制结果中的缩进和空白符,最大缩进空格数为 10,所有大于 10 的值都会自动转换为 10
var book = { 
 "title": "Professional JavaScript", 
 "authors": [ 
 "Nicholas C. Zakas" 
 ], 
 edition: 3, 
 year: 2011 
}
var jsonText = JSON.stringify(book, null, 4); 
保存在 jsonText 中的字符串如下所示:
{ 
 "title": "Professional JavaScript", 
 "authors": [ 
 "Nicholas C. Zakas" 
 ], 
 "edition": 3, 
 "year": 2011 
} 

2.toJSON():

var book = { 
 "title": "Professional JavaScript", 
 "authors": [ 
 "Nicholas C. Zakas" 
 ], 
 edition: 3, 
 year: 2011, 
 toJSON: function(){ 
  return this.title; 
 } 
 }; 
var jsonText = JSON.stringify(book); 
20.2 解析选项

JSON.parse(数据,数组或者函数表示要解析的属性)

var book = { 
 "title": "Professional JavaScript", 
 "authors": [ 
 "Nicholas C. Zakas" 
 ], 
 edition: 3, 
 year: 2011, 
 releaseDate: new Date(2011, 11, 1) 
 }; 
var jsonText = JSON.stringify(book); 
var bookCopy = JSON.parse(jsonText, function(key, value){ 
 if (key == "releaseDate"){ 
 return new Date(value); 
 } else { 
 return value; 
 }  
}); 
alert(bookCopy.releaseDate.getFullYear()); 

你可能感兴趣的:(二十.JSON)