JSON.stringify是一个将JavaScript对象转换为JSON字符串的方法。它的用法有以下几种:
const obj = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(obj, ['name', 'age']);
console.log(jsonString); // {"name":"John","age":30}
const obj = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(obj, null, 2);
console.log(jsonString);
/*
{
"name": "John",
"age": 30,
"city": "New York"
}
*/
const obj = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(obj, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
console.log(jsonString); // {"name":"JOHN","age":30,"city":"NEW YORK"}
const obj = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(obj, (key, value) => {
if (key === 'name') {
return 'Jane';
}
return value;
});
console.log(jsonString); // {"name":"Jane","age":30,"city":"New York"}
const obj = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(obj, null, 2);
console.log(jsonString);
/*
{
"age": 30,
"city": "New York",
"name": "John"
}
*/
总结:JSON.stringify方法可以根据需求灵活地转换JavaScript对象为JSON字符串,并可以选择性地进行过滤、添加空格和缩进、转换函数、替换属性和排序。