ECMAScript有两个特殊的全局变量:Math & JSON
本文主要详解JSON
JSONValue:
JSONNullLiteral
JSONBooleanLiteral
JSONObject
JSONArray
JSONString
JSONNumber
JSONFunction:
- JSON.stringify(jsonvalue, replacerfnorarray, space)
三个参数:
1. json对象,接收的值是json对象包括除了function之外的所有类型
2. 处理函数或者数组,处理函数是对每一个键值对都处理,数组是只过滤留下数组包含的键值,处理函数可以为null
3. space代表缩进字符,如果是number最大不能超过10,如果是字符串就是缩进的字符串
结果:json字符串
有replacer参数的话,返回过滤后的结果,否则返回原生的字符串
过程:
将json-->json字符串
- JSON.parse()
接收的是json字符串,将其格式化为json对象
两个参数:
1. 加单引号的json字符串
2. 过滤函数
结果:
得到格式化的json对象
例子:
JSON.stringify:
- 键值对
- array
- number
- string
- boolean
- null
- function
可见,当值是function时会返回undefined,这个有些情况下并不是我们期望的,那么怎么解决呢,要善于利用第二个参数即replacer为函数时(详解见下面)
// 定义第二个参数为函数,参数需要key&value
function replace (key,value) {
// 判断value类型是否为function
if(typeof value === 'function'){
return Function.prototype.toString.call(value);
}
return value;
}
// 定义一个变量test,某一键值对的值为fn
var test = {'first': 1, 'getFirst': function(){console.log(this.first);}};
// 调用
JSON.stringify(test,replace);
// 结果:
// "{"first":1,"getFirst":"function (){console.log(this.first);}"}"
第二个参数除了可以是function之外还可以是数组[string,number类型的元素],相当于一个IP白名单;
var test = {a:1,b:2,c:3};
JSON.stringify(test,["a"]);
// "{"a":1}"
第二个参数还可以是null,或者不写,会执行JSON.stringify
var test = {a:1,b:2,c:3};
JSON.stringify(test,null);
// "{a:1,b:2,c:3}"
JSON.stringify(test);
// "{a:1,b:2,c:3}"
第三个参数space
- 如果space参数为String类型的情况下,则默认取String的前10个字符作为分割符
- 如果space参数为Number类型的情况下,则表示space个空格(space<=10,大于10取10)
//space参数为String的情况下:
var test = {a:"1",b:2,c:3};
JSON.stringify(test,null,'test')
/*
{
test"a": "1",
test"b": 2,
test"c": 3
}
*/
//space参数为Number的情况下:
var test = {a:"1",b:2,c:3};
JSON.stringify(test,null,4)
/*
{
"a": "1",
"b": 2,
"c": 3
}
三个参数共同控制,将多层嵌套的json对象转换为格式化的美化的json string
// 定义第二个参数为函数,参数需要key&value
function replace (key,value) {
// 判断value类型是否为function
if(typeof value === 'function'){
return Function.prototype.toString.call(value);
}
return value;
}
// 定义一个变量test,某一键值对的值为fn
var test = {'first': 1, 'getFirst': function(){console.log(this.first);}};
// 调用
JSON.stringify(test,replace,4);
// 结果:
/*
"{
"first": 1,
"getFirst": "function (){console.log(this.first);}"
}"
*/
JSON.parse:
两个参数,1json字符串,2replacer function
应用:
数组去重最妙的方法
function replacer(key, value) {
if(typeof value === 'function'){
return Function.prototype.toString.call(value);
}
return value;
}
function unique(arr) {
var hash = {},
re = [];
for (var i = 0, length = arr.length; i < length; i++){
if(!hash[JSON.stringify(arr[i],replacer)]){
re.push(arr[i]);
hash[JSON.stringify(arr[i])] = true;
}
}
return re;
}
unique([function a (){console.log('function')}]);
console.log(unique([1,'1', 1]));
console.log(unique([1,1,5,6,5,78,5,3]));
console.log(unique([1,'1',false,'false',[1,2,3],[1,2],{a:1},{a:1},{b:1}]));
console.log(JSON.stringify(false));
console.log(JSON.stringify('false'));