JSON 使用
2025-02-17
概述
JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,具有以下特点:
- 易于人阅读和编写
- 易于机器解析和生成
- 基于 JavaScript 对象语法
- 与语言无关
JSON 语法
基本规则
| 规则 | 说明 | 示例 |
|---|---|---|
| 数据类型 | 字符串、数字、布尔值、null、对象、数组 | "name", 42, true |
| 字符串 | 必须使用双引号 | "hello" |
| 属性名 | 必须用双引号包围 | {"name": "value"} |
| 不支持 | 函数、undefined、注释 | - |
示例
{
"name": "张三",
"age": 30,
"isStudent": false,
"hobbies": ["读书", "游泳", "编程"],
"address": {
"city": "深圳",
"street": "科技路"
}
}JSON 方法
JSON.stringify()
将 JavaScript 对象转换为 JSON 字符串:
const person = {
name: "张三",
age: 30
};
// 转换为 JSON 字符串
const jsonString = JSON.stringify(person);
console.log(jsonString); // {"name":"张三","age":30}
// 格式化输出
console.log(JSON.stringify(person, null, 2));高级选项
// 第二个参数:替换函数或数组
const replacer = ['name', 'age']; // 只包含这些属性
console.log(JSON.stringify(person, replacer, 2));
// 使用替换函数
const replacerFn = (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
};
console.log(JSON.stringify(person, replacerFn, 2));JSON.parse()
将 JSON 字符串解析为 JavaScript 对象:
const jsonString = '{"name":"张三","age":30}';
// 解析为 JavaScript 对象
const person = JSON.parse(jsonString);
console.log(person.name); // 张三使用 reviver 函数
// 自定义解析过程
const reviver = (key, value) => {
if (key === 'birthDate') {
return new Date(value);
}
return value;
};
const data = JSON.parse('{"birthDate":"2000-01-01"}', reviver);
console.log(data.birthDate instanceof Date); // true实际应用
AJAX 请求
GET 请求
// 获取数据
async function fetchUsers() {
try {
const response = await fetch('/api/users');
const users = await response.json();
return users;
} catch (error) {
console.error('获取用户数据失败:', error);
}
}POST 请求
// 发送 POST 请求
fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: "张三",
age: 30
})
})
.then(response => response.json())
.then(data => console.log(data));数据存储
LocalStorage
// 存储到 localStorage
const user = {
name: "张三",
preferences: {
theme: "dark",
language: "zh-CN"
}
};
localStorage.setItem('user', JSON.stringify(user));
// 读取数据
const savedUser = JSON.parse(localStorage.getItem('user'));
console.log(savedUser.preferences.theme); // "dark"SessionStorage
// 存储到 sessionStorage
sessionStorage.setItem('tempData', JSON.stringify({
id: 1,
timestamp: new Date().toISOString()
}));
// 读取临时数据
const tempData = JSON.parse(sessionStorage.getItem('tempData'));注意事项
数据类型限制
- JSON 不支持 undefined
- 不能序列化函数
- 日期对象会被转换为字符串
// 处理特殊数据类型 const data = { date: new Date(), func: function() {}, undef: undefined, symbol: Symbol(), bigInt: BigInt(123) }; console.log(JSON.stringify(data)); // 输出: {"date":"2023-01-01T00:00:00.000Z"}安全性考虑
- 解析不信任的 JSON 时要小心
- 使用 try-catch 处理解析错误
// 安全的 JSON 解析 try { const data = JSON.parse(jsonString); } catch (error) { console.error('JSON 解析错误:', error); }性能考虑
- 避免频繁的序列化/反序列化
- 大数据量时考虑分批处理
// 分批处理大数据
const largeArray = Array.from({ length: 1000000 }, (_, i) => ({ id: i }));
const batchSize = 1000;
for (let i = 0; i < largeArray.length; i += batchSize) {
const batch = largeArray.slice(i, i + batchSize);
const jsonBatch = JSON.stringify(batch);
// 处理每个批次...
}提示: 在处理大型 JSON 数据时,考虑使用流式解析器以提高性能。