参考JSON.stringify()
此方法将一个js对象转为JSON字符串
参数:JSON.stringify(value[, replacer [, space]])
返回值 JSON字符串
JSON.stringify([new String('string'), new Number(12), new Boolean(true)])
// '["string",12,true]'
JSON.stringify([Symbol(""),function test(){return 12}, undefined,null, Object,NaN,Infinity])
// '[null,null,null,null,null,null,null]'
JSON.stringify(function test(){return 12}) // undefined
JSON.stringify(undefined) // undefined
JSON.stringify(Symbol("")) // undefined
JSON.stringify(Object) // undefined
JSON.stringify(null) // 'null'
JSON.stringify(NaN) // 'null'
JSON.stringify(Infinity) // 'null'
const test = {
fn: function () {
return 'ss'
},
sym: Symbol(''),
un: undefined,
nul: null,
obj: Object,
str: new String('str'),
num: new Number(12),
bool: new Boolean(true)
}
JSON.stringify(test) // '{"nul":null,"str":"str","num":12,"bool":true}'
JSON.stringify(new Date()) // '"2022-11-28T14:55:41.474Z"'
const wrongMap = new Map();
wrongMap['bla'] = 'blaa';
wrongMap['bla2'] = 'blaaa2';
wrongMap.set('we',23)
JSON.stringify(wrongMap)
// '{"bla":"blaa","bla2":"blaaa2"}'
JSON.stringify(
Object.create(
null,
{
x: { value: 'x', enumerable: false },
y: { value: 'y', enumerable: true }
}
)
);
// "{"y":"y"}"
const parentObj = {
name: 'parent',
color: 'red',
toJSON: function () {
return 'bar';
}
};
console.log(JSON.stringify(parentObj, null, '\t'));// "bar"
const parentObj = {
name: 'parent',
color: 'red',
num: 12,
bool: true,
fn: function () {},
parent: 'parent'
};
function replacer(key, val) {
if (['name'].includes(key)) {
return undefined; // 如果为12则返回{"name":12,"color":"red","num":12,"bool":true,"parent":"parent"}
}
return val;
}
console.log(JSON.stringify(parentObj)); // {"name":"parent","color":"red","num":12,"bool":true,"parent":"parent"}
console.log(JSON.stringify(parentObj, replacer)); // {"color":"red","num":12,"bool":true,"parent":"parent"}
console.log(JSON.stringify(parentObj, ['name'])); // {"name":"parent"}
const parentObj = {
name: 'parent',
color: 'red'
};
console.log(JSON.stringify(parentObj, null, 10));
console.log(JSON.stringify(parentObj, null, 900));
console.log(JSON.stringify(parentObj, null, '1234567890a'));
console.log(JSON.stringify(parentObj, null, '\t'));