<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JSON.stringify 方法</title>
</head>
<body>
<pre>
JSON.stringify 方法: 把一个对象通过 stringify 之后提交给后台或者存储在 Storage 里是很常用的手段。
</pre>
<script>
var data = [
{name: "王尼玛", sex:1, age: 30},
{name: "王尼美", sex:0, age: 20},
{name: "王大锤", sex:1, age: 30}
];
var str_json = JSON.stringify(data);
console.log(str_json+"\n");
alert(typeof str_json);
console.log("比如说,我们的数据非常复杂,还有类似头像,昵称,个人签名之类的信息。\n"+
"可是我保存在本地,只需要用户名,和性别,肿么破呢?\n"+
"也许你会说 so easy, 遍历数据重新提取下即可。\n"+
"例如:\n")
var data = [
{name: "王尼玛", sex:1, age: 30},
{name: "王尼美", sex:0, age: 20},
{name: "王大锤", sex:1, age: 30}
];
for (var i=0, new_data=[]; i<data.length; i++) {
new_data.push({
name: data[i].name,
sex: data[i].sex
});
}
var str_json = JSON.stringify(new_data);
console.log(str_json+"\n");
console.log("其实我们只需要用 stringify 第二个参数即可简单处理这种问题。\n")
var data = [
{name: "王尼玛", sex:1, age: 30},
{name: "王尼美", sex:0, age: 20},
{name: "王大锤", sex:1, age: 30}
];
var str_json = JSON.stringify(data, ["name", "sex"]);
console.log(str_json+"\n");
console.log("当然如果我们要更纠结的处理,比如要把 1,0 修改为男女,那么第二个参数可以用回调函数来处理\n");
var data = [
{name: "王尼玛", sex:1, age: 30},
{name: "王尼美", sex:0, age: 20},
{name: "王大锤", sex:1, age: 30}
];
var str_json = JSON.stringify(data, function (k, v) {
if (k === "sex") {
return ["女", "男"][v];
}
return v;
});
console.log(str_json);
console.log("还有第三个参数,用于格式化字符串用的。\n");
var data = [
{name: "王尼玛", sex:1, age: 30},
{name: "王尼美", sex:0, age: 20},
{name: "王大锤", sex:1, age: 30}
];
var str_json = JSON.stringify(data, null, "\t");
console.log(str_json);
str_json = JSON.stringify(data, ["name", "sex"], "\t");
console.log(str_json);
</script>
</body>
</html>
JSON.stringify()方法
最新推荐文章于 2024-07-11 04:17:48 发布