JSON.stringify是一个将JavaScript对象转换为JSON字符串的方法。它的用法有以下几种:
- 将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 =https://www.yisu.com/ask/=='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字符串,并可以选择性地进行过滤、添加空格和缩进、转换函数、替换属性和排序。