[SOLVED] CSV Data Import

Hi, I want to use a remotely downloaded CSV file for my data. How would I do this? I cant find any help on this anywhere, only JSON. Specifically, downloading the CSV file and then reading/parsing it.


This is not PlayCanvas related. You should google how to read CSV in js. There should be plenty of tutorials/examples out there.

Just ask ChatGPT!

Reading a CSV file from a URL with JavaScript can be achieved using the fetch API to retrieve the content and then parse the CSV data. Here’s a simple example to help you get started:

  1. First, you’ll want to fetch the CSV file from the provided URL.
  2. Once you’ve fetched the file, you can then parse its contents.

Here’s an example:

function fetchCSV(url) {
    return fetch(url)
        .then(response => response.text())
        .then(data => csvToArray(data));

function csvToArray(csvString) {
    const rows = csvString.trim().split('\n');
    const header = rows[0].split(',');

    return rows.slice(1).map(rowString => {
        const row = rowString.split(',');
        return header.reduce((accumulator, currentValue, currentIndex) => {
            accumulator[currentValue] = row[currentIndex];
            return accumulator;
        }, {});

// Use the function
const csvURL = 'https://example.com/path/to/csvfile.csv';
fetchCSV(csvURL).then(data => console.log(data));

Some things to note:

  • The above example assumes that the CSV fields are separated by commas and that there aren’t any commas within the fields themselves. In a real-world scenario, you might have CSV data that is more complex, with fields containing commas, newlines, or double-quotes. In such cases, you might want to consider using a dedicated CSV-parsing library like PapaParse.

  • If you’re fetching data from an external URL (a different origin), you need to ensure that the server supports Cross-Origin Resource Sharing (CORS). Otherwise, the browser will block the request due to security concerns.

If you choose to go with PapaParse, the code simplifies significantly:

Papa.parse("https://example.com/path/to/csvfile.csv", {
    download: true,
    header: true,
    complete: function(results) {

With PapaParse, many edge cases in CSV parsing are handled out of the box. If you expect to work with CSV files frequently, especially complex ones, it’s advisable to use a dedicated library.

1 Like

Thanks, although Chat GPT has always been quite useless when it comes to Playcanvas. :slight_smile:

1 Like