Home >Web Front-end >JS Tutorial >How to Read Data From a CSV File Using JavaScript?
CSV (Comma-Separated Values) files are a common format for storing tabular data. To read data from a CSV file using JavaScript, we can use external libraries or implement our own parsing functions.
Using jQuery-CSV Library
jQuery-CSV is a popular library for parsing CSV data in JavaScript. It provides a convenient method, $.csv.toObjects(csv), that automatically maps CSV data to an array of objects.
// Assuming you've included jQuery-CSV in your HTML var data = $.csv.toObjects(csv); // Output [ { heading1: "value1_1", heading2: "value2_1", ... }, { heading1: "value1_2", heading2: "value2_2", ... }, ... ];
Custom Parsing Function
If you don't want to use external libraries, you can create your own parsing function. Here's a simplified example:
function parseCSV(csv) { // Split the CSV into lines var lines = csv.split("\n"); // Extract the header line var headers = lines[0].split(","); // Remove the header line from the CSV lines.shift(); // Loop through the remaining lines and create objects var data = []; for (var i = 0; i < lines.length; i++) { // Split the line into values var values = lines[i].split(","); // Create an object using the headers as keys data.push( Object.fromEntries( headers.map((h, idx) => [h, values[idx]]) ) ); } // Return the parsed data return data; }
Example CSV Data
heading1,heading2,heading3,heading4,heading5 value1_1,value2_1,value3_1,value4_1,value5_1 value1_2,value2_2,value3_2,value4_2,value5_2
Output
[ { heading1: "value1_1", heading2: "value2_1", ... }, { heading1: "value1_2", heading2: "value2_2", ... }, ... ];
Note: The example CSV data does not have line breaks. It's recommended to add line breaks to make the data valid CSV before parsing.
The above is the detailed content of How to Read Data From a CSV File Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!