Professional JavaScript for Web Developers 第四版學習筆記 CHAPTER 23:JSON
Syntax 862
Simple Values 862
Objects 862
Arrays 863
Parsing and Serialization 864
The JSON Object 865
Serialization Options 866
Filtering Results 866
String Indentation 867
The toJSON() Method 868
Parsing Options 869
Summary 870
----------------------------------------------------
JSON.stringify(book, ["title", "edition"]);
let jsonText = JSON.stringify(book, (key, value) => {
switch(key) {
case "authors":
return value.join(",")
case "year":
return 5000;
case "edition":
return undefined;
default:
return value;
}
});
----------------------------------------------------
JSON.stringify(book, null, 4);
JSON.stringify(book, null, "--");
--------------------------------------------------
let book = {
title: "Professional JavaScript",
authors: [
"Nicholas C. Zakas",
"Matt Frisbie"
],
edition: 4,
year: 2017,
toJSON: function() {
return this.title;
}
};
let jsonText = JSON.stringify(book);
console.log(jsonText); //"Professional JavaScript"
toJSON的執(zhí)行優(yōu)先級是最高的。
---------------------------------------------------
let book = {
title: "Professional JavaScript",
authors: [
"Nicholas C. Zakas",
"Matt Frisbie"
],
edition: 4,
year: 2017,
releaseDate: new Date(2017, 11, 1)
};
let jsonText = JSON.stringify(book);
let bookCopy = JSON.parse(jsonText,
(key, value) => key == "releaseDate" ? new Date(value) : value);
alert(bookCopy.releaseDate.getFullYear());