<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
</title>
</head>
<body>
IE8支持 JSON.stringify()
<script>
var book = {
"title": "js",
"author": "kang",
"edition": 3
}
// 1.过滤结果
var res = JSON.stringify(book, [‘title‘, ‘author‘]) console.log(res);
console.log(JSON.parse(res).title);
// 2 自定义数据
var res2 = JSON.stringify(book,
function(key, val) {
switch (key) {
case "title":
return val + ‘es6‘
case "author":
return‘jia‘
case "edition":
return undefined
default:
return val
}
}) console.log(res2);
// 3 格式化
var res3 = JSON.stringify(book, [‘title‘], 2) // 第3个值是格式化属性,可以为数字,代码缩进的空格数,如果是字符串,则是用字符串代替空格来缩进
// var res3=JSON.stringify(book,[‘title‘],‘---‘)
console.log(res3);
// 4 toJSON 不实用
var book2 = {
"title": "es5 es6",
"year": 2017,
toJSON: function() {
return this.title
}
}
console.log(book2.toJSON()); // es5 es6
</script>
</body>
</html>
来源: http://www.bubuko.com/infodetail-2265654.html