将JavaScript对象/数组解析成JSON字符串应该使用 JSON.stringify() 方法。
基本语法
JSON.stringify(value[, replacer[, space]])
常见用法示例
1. 数组转JSON字符串
// 数组示例 let arr = [45, 67, 23, 89, 12]; let jsonStr = JSON.stringify(arr); console.log(jsonStr); // "[45,67,23,89,12]" console.log(typeof jsonStr); // "string"
2. 对象转JSON字符串
// 对象示例
let obj = {
name: "张三",
age: 25,
city: "北京"
};
let jsonStr = JSON.stringify(obj);
console.log(jsonStr);
// "{"name":"张三","age":25,"city":"北京"}"3. 复杂嵌套结构
// 嵌套对象和数组
let data = {
users: [
{id: 1, name: "张三"},
{id: 2, name: "李四"}
],
total: 2,
status: "success"
};
let jsonStr = JSON.stringify(data);
console.log(jsonStr);
// "{"users":[{"id":1,"name":"张三"},{"id":2,"name":"李四"}],"total":2,"status":"success"}"在Web Worker中的应用
发送端使用 JSON.stringify()
// script.js 中 let intArray = [45, 67, 23, 89, 12]; worker.postMessage(JSON.stringify(intArray)); // 发送: "[45,67,23,89,12]"
接收端使用 JSON.parse()
// worker.js 中
onmessage = function(event) {
let intArray = JSON.parse(event.data);
// 接收并解析: [45,67,23,89,12]
}JSON.stringify() 的高级用法
1. 使用replacer函数过滤数据
let obj = {
name: "张三",
age: 25,
password: "123456",
email: "zhangsan@example.com"
};
// 只保留特定字段
let jsonStr = JSON.stringify(obj, ["name", "email"]);
console.log(jsonStr);
// "{"name":"张三","email":"zhangsan@example.com"}"
// 使用函数过滤
let jsonStr2 = JSON.stringify(obj, (key, value) => {
if (key === "password") return undefined; // 排除密码
return value;
});
console.log(jsonStr2);
// "{"name":"张三","age":25,"email":"zhangsan@example.com"}"2. 使用space参数格式化输出
let obj = {
name: "张三",
age: 25,
hobbies: ["读书", "游泳", "编程"]
};
// 格式化输出,方便阅读
let jsonStr = JSON.stringify(obj, null, 2);
console.log(jsonStr);
// {
// "name": "张三",
// "age": 25,
// "hobbies": [
// "读书",
// "游泳",
// "编程"
// ]
// }
// 使用制表符
let jsonStr2 = JSON.stringify(obj, null, "\t");3. 处理特殊值
// undefined、函数、Symbol会被忽略或转为null
let obj = {
name: "张三",
age: undefined, // 会被忽略
sayHello: function() {}, // 会被忽略
score: NaN, // 转为null
date: new Date() // 转为ISO字符串
};
console.log(JSON.stringify(obj));
// "{"name":"张三","score":null,"date":"2024-01-01T00:00:00.000Z"}"4. 自定义toJSON方法
let obj = {
name: "张三",
age: 25,
password: "123456",
toJSON: function() {
return {
name: this.name,
age: this.age
// 故意排除password
};
}
};
console.log(JSON.stringify(obj));
// "{"name":"张三","age":25}" // password被排除实际应用场景
场景1:发送带配置的数据
// script.js
worker.postMessage(JSON.stringify({
numbers: intArray,
filter: 5, // 筛选5的倍数
colorEven: true // 偶数标红
}));
// worker.js
onmessage = function(e) {
let config = JSON.parse(e.data);
let numbers = config.numbers; // [45,67,23,...]
let filter = config.filter; // 5
// 处理数据...
}场景2:保存到localStorage
// 保存数据
let userData = {name: "张三", score: 100};
localStorage.setItem("user", JSON.stringify(userData));
// 读取数据
let savedData = JSON.parse(localStorage.getItem("user"));场景3:AJAX请求发送数据
fetch('/api/users', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name: "张三", age: 25})
});JSON.stringify vs JSON.parse 对比
| 方法 | 作用 | 输入 | 输出 |
|---|---|---|---|
JSON.stringify() | 序列化 | JavaScript对象/数组 | JSON字符串 |
JSON.parse() | 反序列化 | JSON字符串 | JavaScript对象/数组 |
// 双向转换 let originalArray = [1, 2, 3, 4, 5]; let jsonString = JSON.stringify(originalArray); // 数组 → 字符串 let restoredArray = JSON.parse(jsonString); // 字符串 → 数组 console.log(originalArray); // [1, 2, 3, 4, 5] console.log(jsonString); // "[1,2,3,4,5]" console.log(restoredArray); // [1, 2, 3, 4, 5]
总结:
对象/数组 → JSON字符串 用
JSON.stringify()JSON字符串 → 对象/数组 用
JSON.parse()