JSON是什么
JSON,全称是 JavaScript Object Notation,即 JavaScript对象标记法。
JSON的方法
- JSON.stringify()
- JSON.parse()
JSON.stringify(value,replacer,space)
定义:将一个JS对象或值转换为JSON字符串,返回JSON字符串
参数1:要被转换的对象或值
参数2:数组或函数,对序列化的每个属性进行处理,可选
参数3:指定缩进用的字符串,用于美化输出,数字代表多少个空格(1-10),字符串代表该字符串作为缩进,可选,默认没有空格
JSON.stringify([undefined,function test() {},Symbol(""),{ a: 1 },]);
//'[null,null,null,{"a":1}]'
replacer参数
定义:数组或函数格式,对序列化的每个属性进行处理,可选
数组格式 包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中
JSON.stringify({ a: 1, b: 2 }, ["a"]);//'{"a":1}'
函数格式
每个属性都会经过该函数的转换和处理,会按照最顶层属性开始往里,最终达到里层
注意:当遍历到顶层时,传入的形参1会是空字符串 ‘’,形参2是被修改完成的对象,所以得返回该对象
var res = JSON.stringify({ a: 1, b: 2 }, function (prop, v) {
if (prop === "") {
return v;
}
console.log(prop, v);
return v + 1;
});
console.log(res); //'{"a":2,"b":3}'
space参数
定义:用来控制结果字符串里面的间距,数字代表多少个空格(1-10),字符串代表该字符串作为缩进,可选,默认没有空格
常用 \t 换行符
// 使用'\t'制表符
JSON.stringify({ a: 1, b: 2 }, null, "\t");
{
"a": 1,
"b": 2
}
存在的几个特征
- Boolean | Number | String 类型自动会转换为对应原始值
// Boolean对象
let temp =JSON.stringify(new Boolean(1))
console.log(typeof temp) // string
console.log(typeof JSON.parse(temp)) // boolean
// Number对象
let temp =JSON.stringify(new Number(1))
console.log(typeof temp)// string
console.log(typeof JSON.parse(temp))// number
// String对象
let temp =JSON.stringify(new String(1))
console.log(typeof temp)// string
console.log(typeof JSON.parse(temp))// string
- undefined、任意函数、symbol,这三种类型在非数组对象中会被忽略, 在数组中转换成null,在单个值时转换为 undefined
数组对象中 :>> undefined、任意函数、symbol,这三种类型转换为 “null”
// 数组中
let test = () => {};
let arr = [new String(1),test,Symbol("1"),undefined,null];
let temp = JSON.stringify(arr)
console.log(temp);// '["1",null,null,null,null]'
console.log(JSON.parse(temp));// '[1,null,null,null,null]'
非数组对象中 :>> undefined、任意函数、symbol,这三种类型会被忽略
// 非数组对象中
let obj = {
a: new Number(1),
b: ()=>{},
c: Symbol(1),
d:undefined,
e:null
}
let arr = [new String(1),test,Symbol("1"),undefined,null];
console.log(temp);// '["1",null,null,null,null]'
console.log(JSON.parse(temp));// '[1,null,null,null,null]'
- 不可枚举属性会被忽略,数组中不会被忽略
- 如果对象属性通过 get 方式返回对象本身,即循环引用,该属性会被忽略
本文含有隐藏内容,请 开通VIP 后查看