JSON.stringify

JSON.stringify的多种用法总结

小云
108
2023-08-11 13:41:17
栏目: 编程语言

JSON.stringify是一个将JavaScript对象转换为JSON字符串的方法。它的用法有以下几种:

  1. 将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}
  1. 添加额外的空格和缩进,以增加可读性:
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. 对象属性的转换函数:
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. 对象属性的替换:
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. 对象属性排序:
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字符串,并可以选择性地进行过滤、添加空格和缩进、转换函数、替换属性和排序。

0
看了该问题的人还看了