JSON.stringify的多種用法總結(jié)

小云
112
2023-08-11 13:41:17

JSON.stringify是一個(gè)將JavaScript對(duì)象轉(zhuǎn)換為JSON字符串的方法。它的用法有以下幾種:

  1. 將JavaScript對(duì)象轉(zhuǎn)換為JSON字符串,并可以選擇性地將某些屬性進(jìn)行過(guò)濾:
const obj = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(obj, ['name', 'age']);
console.log(jsonString); // {"name":"John","age":30}
  1. 添加額外的空格和縮進(jìn),以增加可讀性:
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"
}
*/
  1. 對(duì)象屬性的轉(zhuǎn)換函數(shù):
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"}
  1. 對(duì)象屬性的替換:
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"}
  1. 對(duì)象屬性排序:
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"
}
*/

總結(jié):JSON.stringify方法可以根據(jù)需求靈活地轉(zhuǎn)換JavaScript對(duì)象為JSON字符串,并可以選擇性地進(jìn)行過(guò)濾、添加空格和縮進(jìn)、轉(zhuǎn)換函數(shù)、替換屬性和排序。

0