JSON.parse() 简单介绍 🎯
🔍 基本作用
将 JSON 字符串 转换为 JavaScript 对象
// JSON 字符串 → JavaScript 对象
const jsonString = '{"name":"张三","age":25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "张三"
console.log(obj.age); // 25
🚀 基本语法
JSON.parse(jsonString)
JSON.parse(jsonString, reviverFunction) // 可选转换函数
📝 使用示例
1. 简单对象转换
const userJSON = '{"name":"李四","active":true}';
const user = JSON.parse(userJSON);
console.log(user.name); // "李四"
console.log(user.active); // true
2. 数组转换
const fruitsJSON = '["苹果","香蕉","橙子"]';
const fruits = JSON.parse(fruitsJSON);
console.log(fruits[0]); // "苹果"
console.log(fruits.length); // 3
3. 嵌套对象
const dataJSON = '{"user":{"name":"王五","age":30},"tags":["A","B"]}';
const data = JSON.parse(dataJSON);
console.log(data.user.name); // "王五"
console.log(data.tags[1]); // "B"
⚠️ 常见错误处理
使用 try-catch
try {
const obj = JSON.parse('无效的JSON字符串');
} catch (error) {
console.error('解析失败:', error.message);
// 使用默认值
const obj = {};
}
安全解析函数
function safeParse(jsonString, defaultValue = {}) {
try {
return JSON.parse(jsonString);
} catch {
return defaultValue;
}
}
const data = safeParse('无效JSON', {name: '默认用户'});
🎯 主要用途
- API 响应处理
- 本地存储数据读取
- 配置文件解析
- 数据传输格式转换
✅ 一句话总结
JSON.parse() 就是把字符串格式的 JSON 数据转换成可以直接使用的 JavaScript 对象!
