Parsing CSV

There is no native CSV parser in JavaScript, but if you have a very small and simple CSV file, you can parse it using JavaScript string manipulation tools or regular expressions, splitting by newlines ( ) to select each row, and then splitting by the delimiter to select each data cell within each row.

Larger data files are more complex, since the preceding code depends on a specific format and does not deal with commas inside quoted strings, missing data, and so on. In this case, you should use a CSV parser. Most examples in this book use the PapaParse CSV parser (papaparse.com) by Matt Holt, which is open source and free. The following code shows how to convert CSV into a JavaScript object using PapaParse:

const csvData = Papa.parse(csvText, {header: true}).data;

If you parsed the example CSV file at the beginning of this section, you will receive an array of objects, and you can list the contents (in the JavaScript console) using the following code (Examples/example-15.html):

csvData.forEach(function(item) {
console.log(item.continent, +item.population, +item.areakm2);
});

The + before the last two properties converts them into numbers. If you don't do that they will be loaded as strings, even though they are numbers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.95.68