JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于前后端数据传输。嵌套JSON数组是指JSON结构中包含多层数组或对象嵌套的情况。
// 示例JSON数据
const data = {
"users": [
{
"id": 1,
"name": "John",
"skills": ["JavaScript", "React", "Node.js"],
"contact": {
"email": "john@example.com",
"phone": "123-456-7890"
}
},
{
"id": 2,
"name": "Jane",
"skills": ["Python", "Django", "SQL"],
"contact": {
"email": "jane@example.com",
"phone": "987-654-3210"
}
}
]
};
// 获取第一个用户的email
const firstUserEmail = data.users[0].contact.email;
console.log(firstUserEmail); // 输出: john@example.com
// 获取所有用户的技能列表
const allSkills = data.users.flatMap(user => user.skills);
console.log(allSkills); // 输出: ["JavaScript", "React", "Node.js", "Python", "Django", "SQL"]
// 使用可选链操作符避免错误
const safeAccess = data.users?.[0]?.contact?.address?.street ?? '默认值';
console.log(safeAccess); // 输出: '默认值'
import json
# 示例JSON数据
data = {
"users": [
{
"id": 1,
"name": "John",
"skills": ["JavaScript", "React", "Node.js"],
"contact": {
"email": "john@example.com",
"phone": "123-456-7890"
}
},
{
"id": 2,
"name": "Jane",
"skills": ["Python", "Django", "SQL"],
"contact": {
"email": "jane@example.com",
"phone": "987-654-3210"
}
}
]
}
# 获取第一个用户的email
first_user_email = data["users"][0]["contact"]["email"]
print(first_user_email) # 输出: john@example.com
# 获取所有用户的技能列表
all_skills = [skill for user in data["users"] for skill in user["skills"]]
print(all_skills) # 输出: ['JavaScript', 'React', 'Node.js', 'Python', 'Django', 'SQL']
# 使用get方法避免KeyError
safe_access = data.get("users", [{}])[0].get("contact", {}).get("address", {}).get("street", "默认值")
print(safe_access) # 输出: '默认值'
原因:当尝试访问嵌套结构中不存在的属性时,会抛出异常或返回undefined/null。
解决方案:
?.
dict.get()
方法原因:API返回的数据结构可能有变化,某些字段可能缺失。
解决方案:
原因:深度嵌套和大数据量可能导致解析缓慢。
解决方案:
function findInNested(data, targetKey) {
if (data === null || typeof data !== 'object') {
return null;
}
if (data.hasOwnProperty(targetKey)) {
return data[targetKey];
}
for (const key in data) {
const result = findInNested(data[key], targetKey);
if (result !== null) {
return result;
}
}
return null;
}
// 使用示例
const result = findInNested(data, 'email');
console.log(result); // 输出第一个找到的email值
通过掌握这些方法和技巧,你可以高效地从各种嵌套JSON结构中提取所需数据。
没有搜到相关的文章