JSON.stringify的多种用法总结


JSON.stringify是一个将JavaScript对象转换为JSON字符串的方法。它的用法有以下几种:
1. 将JavaScript对象转换为JSON字符串,并可以选择性地将某些属性进行过滤:
```javascript
const obj = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(obj, ['name', 'age']);
console.log(jsonString); // {"name":"John","age":30}
```
2. 添加额外的空格和缩进,以增加可读性:
```javascript
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"
}
*/
```
3. 对象属性的转换函数:
```javascript
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"}
```
4. 对象属性的替换:
```javascript
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"}
```
5. 对象属性排序:
```javascript
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字符串,并可以选择性地进行过滤、添加空格和缩进、转换函数、替换属性和排序。


上一篇:一文教你快速生成MySQL数据库关系图

下一篇:vim编辑器常用命令总结


Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器