如何在JavaScript中将API获取的JSON中AV01字段存入变量
从API返回的JSON中提取并存储AV01字段值
根据你提供的JSON结构,AV01字段嵌套在多层数组与对象中,需要逐层访问才能提取。以下是具体实现方案:
基础提取代码
适用于确定results和records数组至少包含一个元素的场景:
fetch('你的实际API地址') .then(res => res.json()) .then(data => { // 按层级访问:data → results数组第一个元素 → records数组第一个元素 → AV01字段 const av01Value = data.results[0].records[0].AV01; // 此时av01Value变量已存储目标值,可直接用于后续操作 console.log('AV01字段值:', av01Value); }) .catch(err => console.error('API请求失败:', err));
安全处理版本
如果不确定数组是否存在有效元素,建议添加判断避免代码报错:
fetch('你的实际API地址') .then(res => res.json()) .then(data => { let av01Value; // 检查results数组是否存在且有元素 if (data.results?.length) { const targetTransaction = data.results[0]; // 检查records数组是否存在且有元素 if (targetTransaction.records?.length) { av01Value = targetTransaction.records[0].AV01; console.log('AV01字段值:', av01Value); // 此处执行需要用到av01Value的业务逻辑 } else { console.log('未找到有效records数据'); } } else { console.log('未找到有效results数据'); } }) .catch(err => console.error('API请求失败:', err));
多元素场景处理
如果results或records包含多个元素,可通过循环提取所有AV01值:
fetch('你的实际API地址') .then(res => res.json()) .then(data => { const allAv01Values = []; if (data.results?.length) { data.results.forEach(transaction => { if (transaction.records?.length) { transaction.records.forEach(record => { allAv01Values.push(record.AV01); }); } }); } console.log('所有AV01字段值:', allAv01Values); // 后续可对allAv01Values数组进行批量操作 }) .catch(err => console.error('API请求失败:', err));
内容的提问来源于stack exchange,提问作者Anghelo Fernandez Alvarado
相关产品推荐
相关产品推荐

