[JavaScript] Using CSV on the server and converting it to JSON

This article can be read in about 4 minutes.
PR

The purpose

I want to convert a CSV file on a server into JSON on the client side for use.

I’ll be using the node-csvtojson library. This assumes that Node.js is already installed.

GitHub - Keyang/node-csvtojson: Blazing fast and Comprehensive CSV Parser for Node.JS / Browser / Command Line.
Blazing fast and Comprehensive CSV Parser for Node.JS / Browser / Command Line. - GitHub - Keyang/node-csvtojson: Blazing fast and Comprehensive CSV Parser for...

All data will be downloaded to the client, so please consider an alternative method for sensitive data like user information or for large datasets.

PR

Preparation

Run the following command in your project’s root directory to install csvtojson.

npm i csvtojson
PR

Implementation

The implementation is as follows.

import csv from "csvtojson"

const convertCsv2Json = (txt) => {
  csv().fromString(txt).then(
    csv_data => {
      console.log(csv_data);
    }
  )
}

const fetchSetting = async (url) => {
  fetch(url).then(res => res.text().then(txt => convertCsv2Json(txt)));
}

fetchSetting("/setting.csv")

In fetchSetting, a CSV file is downloaded and then convertCsv2Json is called. (The /setting.csv argument is the URL of the CSV file, so please change it as needed).

The downloaded CSV is converted to JSON in convertCsv2Json.

The converted JSON is available as csv_data within the following function.

    csv_data => {
      console.log(csv_data);
    }

Japanese characters may be garbled. Please save the CSV file in UTF-8

Execution example

Here are examples of input CSV and output JSON.

The first row will be treated as the header.

/setting.csv

Name,Age,Country
Taro,25,Japan
Tom,21,USA

csv_data

Other output format

You can change the output by passing arguments to csv().

csv({ noheader: true, output: “csv” })

Under this setting, the first row is also treated as data, and the data is saved as an array.

/setting.csv

Name,Age,Country
Taro,25,Japan
Tom,21,USA

csv_data

csv({ output: “line” })

In this setting, the data will be saved as a single string.

/setting.csv

Name,Age,Country
Taro,25,Japan
Tom,21,USA

csv_data

comment

Copied title and URL