JSON
JSON
JSON全称JavaScript Object Notation(JavaScript 对象表示法),JSON语法可以有三种类型的值,分别是简单值(字符,数字,布尔值和null),对象和数组。
JSON解析与序列化
JSON对象的两个方法:
stringify():把JavaScript对象序列化为JSON字符串。
parse():把JSON字符串解析为原生JavaScript值
var book = {
"title": "Professional JavaScript",
"authors": [
"Nicholas C. Zakas"
],
edition: 3,
year: 2011
};
var jsonText = JSON.stringify(book);
alert(jsonText);//结果:{"title":"Professional JavaScript","authors":["Nicholas C. Zakas"],"edition":3,"year":2011}
var bookCopy = JSON.parse(jsonText);
alert(bookCopy.title);//结果:Professional JavaScript
JSON.stringify()除了JavaScript对象外,还可以接受第二个参数,可以是数组或者函数
var book = {
title: "Professional JavaScript",
authors: [
"Nicholas C. Zakas"
],
edition: 3,
year: 2011
};
var jsonText = JSON.stringify(book, ["title", "edition"]);//参数:数组,起过滤作用
alert(jsonText);
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;
}
});
alert(jsonText);
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);
alert(jsonText);
var bookCopy = JSON.parse(jsonText, function(key, value){
if (key == "releaseDate"){
return undefined;
} else {
return value;
}
});
alert("releaseDate" in bookCopy);