KamSami
KamSami

Reputation: 407

Trying to parse csv file into array of objects

I have stored CSV files within my application. I want to convert it to an array of objects. I'm using csv-parse. https://www.npmjs.com/package/csv-parse

error message for just requiring the csv file

error:

Ingredient #, Ingredient Description, Cycle Count ^

SyntaxError: Invalid or unexpected token

const parse = require('csv-parse/lib/sync');
const assert = require('assert');
const router = require('express').Router();
const count = require("./csv/IngCountCycle.csv");

router.get('/', function () {
    console.log("HI");

    const input = `
"key_1","key_2"
"value 1","value 2"
`;
    const records = parse(input, {
        columns: true,
        skip_empty_lines: true
    });

    console.log(records)
    //output ([{key_1: 'value 1', key_2: 'value 2'}])
});

module.exports = router;

test.csv

Ingredient #, Ingredient Description, Cycle Count
1,GUACAMOLE,Annually,
2,GUACAMOLE,Period,
3,GUACAMOLE,Weekly,
4,GUACAMOLE,Custom

testParse.js

const parse = require('csv-parse/lib/sync');
const assert = require('assert');
const router = require('express').Router();
const count = require("./csv/IngCountCycle.csv");

router.get('/', function () {
    const input = count;
    const records = parse(input, {
        columns: true,
        skip_empty_lines: true
    });

    console.log(records)
});

module.exports = router;

Upvotes: 0

Views: 4156

Answers (2)

tagyoureit
tagyoureit

Reputation: 1286

You have an extra , (comma) on lines 1, 2 and 3 but not 4. Your header line has 3 commas. You either need to clean the data before using it or account for this discrepancy in your data with some code.

Upvotes: 1

Guilherme Lemmi
Guilherme Lemmi

Reputation: 3487

Seems like CSVParse is not being able to interpret your row delimiter. Could you confirm that you are using one of the supported options for row delimiter, as specified in the docs (check option record_delimiter)?

Then, try to be explicit about which delimiter you are using, like below:

const records = parse(input, {
    columns: true,
    skip_empty_lines: true,
    record_delimiter: "\n"
});

Upvotes: 0

Related Questions