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字符串,并可以選擇性地進行過濾、添加空格和縮進、轉換函數、替換屬性和排序。