DEV Community

Sanchit Gupta
Sanchit Gupta

Posted on

Snippet... Working with CSV in Javascript with PapaParse

https://www.apps4developers.com/csv/

Installing papaparse

Install PapaParse library from npm.

npm install papaparse
Enter fullscreen mode Exit fullscreen mode

Learn more about PapaParse here.

CSV to JSON With Header

import Papa from 'papaparse';

const csvString = `Column 1,Column 2,Column 3,Column 4
1-1,1-2,1-3,1-4
2-1,2-2,2-3,2-4
3-1,3-2,3-3,3-4
4,5,6,7`;
const jsonObj = Papa.parse(csvString, { header: true })

console.log(jsonObj);
Enter fullscreen mode Exit fullscreen mode

CSV to JSON Without Header

import Papa from 'papaparse';

const csvString = `1-1,1-2,1-3,1-4
2-1,2-2,2-3,2-4
3-1,3-2,3-3,3-4
4,5,6,7`;
const jsonObj = Papa.parse(csvString, { header: false })

console.log(jsonObj);
Enter fullscreen mode Exit fullscreen mode

Convert JSON to CSV

import Papa from 'papaparse';

const jsonObj = [
    {
        "Column 1": "1-1",
        "Column 2": "1-2",
        "Column 3": "1-3",
        "Column 4": "1-4"
    },
    {
        "Column 1": "2-1",
        "Column 2": "2-2",
        "Column 3": "2-3",
        "Column 4": "2-4"
    },
    {
        "Column 1": "3-1",
        "Column 2": "3-2",
        "Column 3": "3-3",
        "Column 4": "3-4"
    },
    {
        "Column 1": 4,
        "Column 2": 5,
        "Column 3": 6,
        "Column 4": 7
    }
];
const csvString = Papa.unparse(jsonObj, { header: false })

console.log(csvString);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)