函数声明
1、JSON.stringify = function (value, replacer, space);
2、JSON.parse = function (text, reviver);
一、JSON.stringify的使用
先定义数组和函数(对象的构造函数)
// 学生对象构造函数
function student(id, name, sex, age)
{
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
function replacer(key, value)
{
if (("name" === key) || ("lizi" === key))
{
return value.toString().toUpperCase();
}
if ((true === !key)||""===key)
{
return value.toString().toUpperCase();
}
return value;
}
var fruit = ["苹果", "香蕉", "西瓜", "橘子", "桃子", "lizi", "putao"];
var field = ["id", "name", "class", "grade", "lizi"];
var p1 = new student(1, "xulh", "男", 25);
var studentAry = [new student(1, "xulh", "男", 25), new student(2, "chexx", "女", 27)];
1、一个参数JSON.stringify
// 对象
var sJson = JSON.stringify(p1);
// 结果:"{"id":1,"name":"xulh","sex":"男","age":25}"
// 数组
sJson = JSON.stringify(fruit);
// 结果:"["苹果","香蕉","西瓜","橘子","桃子","lizi","putao"]"
2、两个参数JSON.stringify
// 对象 - 数组:用数组中的字段过滤对象
sJson = JSON.stringify(p1, field);
// 结果:"{"id":1,"name":"xulh"}"
sJson = JSON.stringify(p1, fruit);
// 结果:"{}"
// 对象 - 对象:是有问题的
sJson = JSON.stringify(p1, replacer);
// 结果:""[OBJECT OBJECT]""
// 数组 - 对象:看似正确,但是是有问题的,多了一对双引号
sJson = JSON.stringify(fruit, replacer);
// 结果:""苹果,香蕉,西瓜,橘子,桃子,LIZI,PUTAO""
// 数组 - 数组:第二个数组被忽略
sJson = JSON.stringify(fruit, field);
// 结果:"["苹果","香蕉","西瓜","橘子","桃子","lizi","putao"]"
3、三个参数JSON.stringfy
第三个参数是为了格式化json字符串的;
如果省略的话,那么显示出来的值 就没有分隔符。直接输出来;
如果是一个数字,那么它就定义缩进几个字符,如果大于10 ,则最大值为10;
如果是一些转义字符,比如“\t”,表示回车,那么它每行一个回车;
如果仅仅是字符串,那么就在每行输出值的时候把这些字符串附加上去。当然,最大长度也是10个字符;