是否可以使用 Javascript fetch API 读取 .csv 文件?

Kar*_*sad 1 javascript frontend

喜欢

fetch('state_wise_data.csv')
   .then(response => response.json())
   .then(data => console.log(data))
   .catch(err => console.log(err))
Run Code Online (Sandbox Code Playgroud)

尝试这样做,但没有奏效。

Sar*_*unt 7

Fetch 100% 使用 .csv 文件(甚至使用 req.query 的 api)。'content-type': 'text/csv' 必须在获取的标头中进行处理:{},并使用 res.text() 而不是 res.json() 来解释数据。

const downloadCsv = async () => {
    try {
        const target = `https://SOME_DOMAIN.com/data/csv/addresses.csv`; //file
        //const target = `https://SOME_DOMAIN.com/api/data/log_csv?$"queryString"`; //target can also be api with req.query
        
        const res = await fetch(target, {
            method: 'get',
            headers: {
                'content-type': 'text/csv;charset=UTF-8',
                //'Authorization': //in case you need authorisation
            }
        });

        if (res.status === 200) {

            const data = await res.text();
            console.log(data);

        } else {
            console.log(`Error code ${res.status}`);
        }
    } catch (err) {
        console.log(err)
    }
}
Run Code Online (Sandbox Code Playgroud)


Kir*_*aLT 6

首先,CSV它不是一个JSON. Fetch 不支持 CSV,您需要下载 CSV 字符串(您可以使用response.text())并使用第三方 CSV 解析器。

对于解析 CSV 解析器,您可以使用papaparse

“解析 CSV 不就是 String.split(',') 吗?”

天堂,没有。爸爸做对了。只需传入带有可选配置的 CSV 字符串。

例子:

const response = fetch('state_wise_data.csv')
   .then(response => response.text())
   .then(v => Papa.parse(v))
   .catch(err => console.log(err))

response.then(v => console.log(v))
Run Code Online (Sandbox Code Playgroud)

它还支持文件下载:

Papa.parse('state_wise_data.csv', {
    download: true,
    complete: results => {
        console.log(results);
    }
})
Run Code Online (Sandbox Code Playgroud)


Tin*_*sae 0

CSV 不是 JSON 文件类型,因此无法解析为 json 文本。您可以在此处检查如何在 javascript 中解析 CSV 文本:Example JavaScript code to parse CSV data