1.经典用法
var data = [
{name: "悟空", sex:1, age: 30},
{name: "八戒", sex:0, age: 20},
{name: "唐僧", sex:1, age: 30}
];//JavaScript数组中包含对象
//将JavaScript对象转换为JSON格式的字符串
var str_json = JSON.stringify(data);
console.log(str_json);
//运行结果为:
//[{"name":"悟空","sex":1,"age":30},{"name":"八戒","sex":0,"age":20},{"name":"唐僧","sex":1,"age":30}]
复制代码
So easy! 这个也是我们最常用的方式
2.复杂数据的提取
比如说,我们的数据非常复杂,还有类似头像,昵称,个人签名之类的信息。可是我保存在本地,只需要用户名和性别,如果操作呢?我们可以通过提供的第二参数搞定,遍历数据重新提取下即可。
a.传统方式提取数据思路
var data = [
{name: "悟空", sex:1, age: 30},
{name: "八戒", sex:0, age: 20},
{name: "唐僧", sex:1, age: 30}
];
//传统方式提取数据
var new_data = [];
for (var i=0, new_data=[]; i<data.length; i++) {
//构建行的数组
new_data.push({
name: data[i].name,
sex: data[i].age
});
}
var str_json = JSON.stringify(new_data);
console.log(str_json);
复制代码
b.使用stringify的第二参数搞定提取数据
var data = [
{name: "悟空", sex:1, age: 30},
{name: "八戒", sex:0, age: 20},
{name: "唐僧", sex:1, age: 30}
];
var str_json = JSON.stringify(data,["name","age"]);
console.log(str_json);
//运行结果
//[{"name":"悟空","age":30},{"name":"八戒","age":20},{"name":"唐僧","age":30}]
复制代码
第二个参数只要传入需要的keys数组,就非常轻松的就完成这种处理了。
当然如果我们要更纠结的处理,比如要把 1,0 修改为男女,那么第二个参数可以用回调函数来处理。
var data = [
{name: "悟空", sex:1, age: 30},
{name: "八戒", sex:0, age: 20},
{name: "唐僧", sex:1, age: 30}
];
var str_json = JSON.stringify(data,function (key, value) {
if(key==="sex"){
return ["男生","女生"][value];
}
return value;
});
console.log(str_json);
// [{"name":"悟空","sex":"女生","age":30},{"name":"八戒","sex":"男生","age":20},{"name":"唐僧","sex":"女生","age":30}]
复制代码
3.第三个参数"吴用"
非常鸡肋的一个参数,基本没有用过,看自己的情况!
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"],"\t");
console.log(str_json);
/*
[
{
"name": "悟空",
"sex": 1
},
{
"name": "八戒",
"sex": 0
},
{
"name": "唐僧",
"sex": 1
}
]
*/
复制代码
不懂请查看api