JSON格式相关规定:javascript
JSON格式处理器:java
JSON字符串:正则表达式
JSON处理器有两个静态方法:数组
JSON.parse()
JSON.stringify()
JSON.stringify()
浏览器
将其余类型的值转换为JSON字符串函数
JSON的第二个参数(不经常使用到,这部分可忽略):ui
JSON还有第三个参数,也不经常使用到,感兴趣的朋友可参考其余文档spa
console.log(JSON.stringify(123)); //'123'
console.log(JSON.stringify('123')); //'"123"'
console.log(JSON.stringify(true)); // 'true'
console.log(JSON.stringify('true')); //'"true"'
console.log(JSON.stringify(null)); //'null'
console.log(JSON.stringify({ name: 'Tom' })); //'{"name":"Tom"}'
console.log(JSON.stringify({ undefined, name: 'Tom' })); //'{"name":"Tom"}' 对象中的undefined被浏览器过滤掉
console.log(JSON.stringify([1, { name: 'Tom' }])); //'[1,{"name":"Tom"}]'
console.log(JSON.stringify([undefined, { name: 'Tom' }])); //'[null,{"name":"Tom"}]' 数组中的undefined转为null
console.log(JSON.stringify(/^\d$/)); //{} 正则会转为空对象
复制代码
//JSON的第二个参数:指定能够转换成JSON字符串的属性
let obj = {
name: 'Tom',
age: 18,
id: 123
}
console.log(JSON.stringify(obj, ['name', 'id'])); //'{"name":"Tom","id":123}'
复制代码
//JSON.stringify方法的第二个参数是函数的状况
function fn() {
return 123
};
console.log(JSON.stringify({ a: 1 }, fn)); //'123'
function fn1(key, value) {
typeof value === 'number' ? value++ : null; //为何这非得先判断一下呢,直接写下面的value++就不能够 ,我也不明白为何
// value++
return value
};
console.log(JSON.stringify({ a: 1, b: 2 }, fn1)); //{"a":2,"b":4}
function fn3(key, value) {
typeof value === 'string' ? value = 'Jerry' : null;
// value = 'Jerry'
return value
};
console.log(JSON.stringify({ name: 'Tom' }, fn3)); //{"name":"Jerry"}
复制代码
JSON.parse()
将 JSON 字符串转换成其余值console.log(JSON.parse('123')); //123
console.log(JSON.parse('"123"')); //"123"
console.log(JSON.parse('true')); //true
console.log(JSON.parse('null')); //null
console.log(JSON.parse('{"name":"Tom"}')); //{name: "Tom"}
复制代码
//JSON.parse()的第二个参数是函数的状况
function f(key, value) {
if (key === 'a') {
return value + 10;
}
return value;
}
console.log(JSON.parse('{"a": 1, "b": 2}', f)); // {a: 11, b: 2}
复制代码