javascript中json基础知识详解(3)

var person = JSON.parse('{"name":"Lao Wang","age":21}',function(key,value){ if(key == "age"){ return undefined; }else{ return value; } }); console.log(person.name); // Lao Wang

在将日期字符串转换为 Date 对象时,经常要用到还原函数

var book = { "title": "Professional JavaScript", "authors": ["Nicholas C. Zakas"], edition: 3, year: 2011, releaseDate: new Date(2017, 1, 18) }; var jsonText = JSON.stringify(book,null,4); console.log(jsonText); /* { "title": "Professional JavaScript", "authors": [ "Nicholas C. Zakas" ], "edition": 3, "year": 2011, "releaseDate": "2017-02-17T16:00:00.000Z" } */ var bookCopy = JSON.parse(jsonText, function(key, value){ if (key == "releaseDate"){ return new Date(value); }else{ return value; } }); console.log(bookCopy.releaseDate.getFullYear()); // 2017

参考资料:

JSON对象 详解及实例代码

JavaScript高级程序设计中文版第三版

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwdgss.html