JSON 在 JavaScript 中的使用
JSON 与 JavaScript
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它与 JavaScript 对象字面量语法非常相似。在 JavaScript 中,我们可以轻松地处理 JSON 数据。
{"{}"}
JSON.parse()
将 JSON 字符串转换为 JavaScript 对象
" "
JSON.stringify()
将 JavaScript 对象转换为 JSON 字符串
JSON.parse() - 解析 JSON 字符串
JSON.parse() 方法用于将一个 JSON 字符串转换为 JavaScript 对象。
const jsonString = '{"name": "张三", "age": 30, "isStudent": false}';
const obj = JSON.parse(jsonString);
console.log(obj.name);
console.log(obj.age);
console.log(obj.isStudent);
使用 reviver 函数
reviver 函数可以在解析过程中对结果进行转换。
const jsonString = '{"name": "张三", "age": 30, "birthDate": "1990-05-15"}';
const obj = JSON.parse(jsonString, function(key, value) {
if (key === 'birthDate') {
return new Date(value);
}
return value;
});
console.log(obj.birthDate);
console.log(obj.birthDate.getFullYear());
提示: 始终使用 try-catch 处理 JSON.parse() 可能抛出的异常,特别是处理来自外部源的 JSON 数据时。
JSON.stringify() - 序列化 JavaScript 对象
JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。
const obj = {
name: "张三",
age: 30,
isStudent: false,
hobbies: ["阅读", "游泳"]
};
const jsonString = JSON.stringify(obj);
console.log(jsonString);
格式化输出
使用第三个参数可以格式化输出,提高可读性。
const obj = {
name: "张三",
age: 30,
address: {
city: "北京",
country: "中国"
}
};
const formattedJson = JSON.stringify(obj, null, 2);
console.log(formattedJson);
使用 replacer 函数
replacer 函数可以控制哪些属性被包含在结果中。
const obj = {
name: "张三",
age: 30,
password: "secret123",
isAdmin: true
};
const jsonString = JSON.stringify(obj, function(key, value) {
if (key === 'password') {
return undefined;
}
return value;
});
console.log(jsonString);
交互式演示
在下面的演示区域中,您可以尝试 JSON 解析和序列化。
JSON 数据操作
解析后的 JSON 数据可以像普通 JavaScript 对象一样进行操作。
const jsonString = '{"users": [{"id": 1, "name": "张三"}, {"id": 2, "name": "李四"}]}';
const data = JSON.parse(jsonString);
console.log(data.users[0].name);
data.users[0].name = "张四";
data.users.push({id: 3, name: "王五"});
const updatedJson = JSON.stringify(data, null, 2);
console.log(updatedJson);
遍历 JSON 数据
const data = {
name: "张三",
age: 30,
hobbies: ["阅读", "游泳"]
};
for (let key in data) {
if (data.hasOwnProperty(key)) {
console.log(key + ": " + data[key]);
}
}
Object.keys(data).forEach(key => {
console.log(`${key}: ${data[key]}`);
});
data.hobbies.forEach((hobby, index) => {
console.log(`爱好 ${index + 1}: ${hobby}`);
});
实际应用场景
1. AJAX 请求
fetch('/api/users')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('请求失败:', error);
});
const userData = {
name: "张三",
email: "zhangsan@example.com"
};
fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(userData)
});
2. 本地存储
const userSettings = {
theme: "dark",
language: "zh-CN",
notifications: true
};
localStorage.setItem('userSettings', JSON.stringify(userSettings));
const storedSettings = JSON.parse(localStorage.getItem('userSettings'));
if (storedSettings) {
console.log("用户设置:", storedSettings);
}
3. 配置文件
fetch('config.json')
.then(response => response.json())
.then(config => {
const apiUrl = config.api.baseUrl;
const timeout = config.api.timeout;
});
注意事项
1. 错误处理
始终使用 try-catch 处理 JSON.parse() 可能抛出的异常:
function safeParse(jsonString) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.error('JSON 解析错误:', error.message);
return null;
}
}
2. 数据类型限制
JSON 不支持 JavaScript 中的所有数据类型:
- 函数 - 序列化时会被忽略
- undefined - 序列化时会被忽略
- Symbol - 序列化时会被忽略
- 循环引用 - 会导致序列化错误
3. 性能优化
对于大型 JSON 数据:
- 使用流式解析处理大型数据集
- 只序列化需要的属性,减少数据量
- 对于频繁操作的对象,缓存序列化结果