本文旨在解决从csv格式的api获取数据时,变量填充失败的问题。我们将深入探讨如何正确识别csv数据源的列名,利用`fetch` api和`papaparse`库进行数据获取、解析、筛选和类型转换,最终实现数据的准确提取和在控制台的展示,并提供一套完整的javascript代码实践方案。
在现代Web开发中,从外部API获取数据是常见的任务。当API返回的数据是CSV格式时,正确地解析和提取所需信息至关重要。许多开发者在尝试将API数据填充到JavaScript变量时遇到困难,常见的原因是未能准确识别CSV数据源中的列名。本教程将通过一个具体的案例,详细讲解如何解决这类问题。
当尝试从CSV API获取数据并将其存储到变量中时,如果变量始终为空或未按预期工作,最常见的原因是代码中引用的数据字段名与CSV文件实际的列名不匹配。
以本案例为例,原始代码尝试使用 row["INSTNM"]、row["CURROPER"] 和 row["TUITIONFEE_IN"] 来访问数据。然而,提供的CSV文件 (https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/tuition_cost.csv) 实际的头部(列名)是 name、degree_length 和 in_state_tuition 等。这种不匹配导致 PapaParse 解析后的数据对象中找不到对应的属性,从而使得变量无法被正确填充。
关键点: 始终验证API返回数据的实际结构,特别是CSV文件的列头。
立即学习“Java免费学习笔记(深入)”;
为了克服上述挑战,我们需要调整数据访问逻辑,使其与CSV文件的实际列名保持一致。以下是详细的步骤和代码实现。
首先,我们使用fetch API获取CSV文件的内容,然后利用PapaParse库将其解析为JavaScript对象数组。PapaParse是一个功能强大的CSV解析器,能够轻松处理复杂的CSV数据。
// Function to retrieve school information function getSchoolInformation() { const schoolName = document.getElementById("schoolName").value; console.log("尝试查询学校:", schoolName); // 辅助调试 fetch('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/tuition_cost.csv') .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.text(); }) .then(csvData => { const schoolInfo = findSchoolInformation(schoolName, csvData); displaySchoolInformation(schoolInfo); }) .catch(error => { console.error('获取或解析数据时发生错误:', error); }); }
代码解析:
这是解决问题的核心步骤。在 findSchoolInformation 函数中,我们使用 PapaParse.parse() 方法解析CSV数据。解析后,parsedData 将是一个对象数组,每个对象代表CSV的一行,其属性名就是CSV的列头。
我们需要根据CSV文件的实际列名来访问数据。通过查看原始CSV文件,我们可以确定正确的列名是 name、degree_length 和 in_state_tuition。
// Function to find school information based on school name function findSchoolInformation(schoolName, csvData) { const parsedData = Papa.parse(csvData, { header: true, // 告诉PapaParse第一行是列头 skipEmptyLines: true // 跳过空行 }).data; const schoolInfo = []; parsedData.forEach(function(row) { // 修正:使用CSV文件中实际的列名 const collegeName = row.name; const degreeLength = row.degree_length; const tuitionCost = row.in_state_tuition; // 进行大小写不敏感的学校名称匹配 if (collegeName && collegeName.toLowerCase() === schoolName.toLowerCase()) { // 匹配成功后,对数据进行类型转换 const parsedDegreeLength = parseInt(degreeLength); const parsedTuitionCost = parseFloat(tuitionCost); // 确保转换后的数据是有效的数字 if (!isNaN(parsedDegreeLength) && !isNaN(parsedTuitionCost)) { schoolInfo.push({ collegeName: collegeName.toLowerCase(), // 统一存储为小写 degreeLength: parsedDegreeLength, tuitionCost: parsedTuitionCost }); } } }); console.log('找到的学校信息:', schoolInfo); // 辅助调试 return schoolInfo; }
代码解析:
最后,我们将筛选并处理过的学校信息展示在控制台。
// Function to display school information in the console function displaySchoolInformation(schoolInfo) { if (schoolInfo.length === 0) { console.log("未找到匹配的学校信息。"); return; } console.log("\n--- 查询结果 ---"); for (let i = 0; i < schoolInfo.length; i++) { const collegeName = schoolInfo[i].collegeName; const degreeLength = schoolInfo[i].degreeLength; const tuitionCost = schoolInfo[i].tuitionCost; console.log("学校名称: " + collegeName); console.log("学制长度: " + degreeLength + " 年"); console.log("州内学费: $" + tuitionCost.toFixed(2)); // 格式化学费为两位小数 console.log("------------------------------"); } }
代码解析:
为了让用户能够输入学校名称并触发查询,我们需要一个简单的HTML页面。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>学校信息查询</title> <!-- 引入PapaParse库 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script> </head> <body> <label for="schoolName">输入学校名称:</label> <input type="text" id="schoolName" value="Duke University" /> <button onclick="getSchoolInformation()">获取信息</button> <script> // 将上面的JavaScript函数代码放在这里 // getSchoolInformation(), findSchoolInformation(), displaySchoolInformation() // ... // Function to retrieve school information function getSchoolInformation() { const schoolName = document.getElementById("schoolName").value; console.log("尝试查询学校:", schoolName); fetch('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/tuition_cost.csv') .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.text(); }) .then(csvData => { const schoolInfo = findSchoolInformation(schoolName, csvData); displaySchoolInformation(schoolInfo); }) .catch(error => { console.error('获取或解析数据时发生错误:', error); }); } // Function to find school information based on school name function findSchoolInformation(schoolName, csvData) { const parsedData = Papa.parse(csvData, { header: true, skipEmptyLines: true }).data; const schoolInfo = []; parsedData.forEach(function(row) { const collegeName = row.name; const degreeLength = row.degree_length; const tuitionCost = row.in_state_tuition; if (collegeName && collegeName.toLowerCase() === schoolName.toLowerCase()) { const parsedDegreeLength = parseInt(degreeLength); const parsedTuitionCost = parseFloat(tuitionCost); if (!isNaN(parsedDegreeLength) && !isNaN(parsedTuitionCost)) { schoolInfo.push({ collegeName: collegeName.toLowerCase(), degreeLength: parsedDegreeLength, tuitionCost: parsedTuitionCost }); } } }); console.log('找到的学校信息:', schoolInfo); return schoolInfo; } // Function to display school information in the console function displaySchoolInformation(schoolInfo) { if (schoolInfo.length === 0) { console.log("未找到匹配的学校信息。"); return; } console.log("\n--- 查询结果 ---"); for (let i = 0; i < schoolInfo.length; i++) { const collegeName = schoolInfo[i].collegeName; const degreeLength = schoolInfo[i].degreeLength; const tuitionCost = schoolInfo[i].tuitionCost; console.log("学校名称: " + collegeName); console.log("学制长度: " + degreeLength + " 年"); console.log("州内学费: $" + tuitionCost.toFixed(2)); console.log("------------------------------"); } } </script> </body> </html>
HTML解析:
通过本教程,我们了解了从CSV格式API中提取数据时,变量填充失败的常见原因及其解决方案。核心在于准确识别CSV数据的列名,并结合fetch API进行数据获取,PapaParse进行高效解析,以及细致的数据筛选和类型转换。遵循这些实践,可以确保从API获取的数据能够被正确地处理和利用,从而构建出更加健壮和可靠的Web应用程序。
以上就是如何从CSV API中准确提取和处理数据:JavaScript实践指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号