Security News
tea.xyz Spam Plagues npm and RubyGems Package Registries
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
actual-csv-to-json-parser
Advanced tools
Don't waste time with the other csv to json parsers. I tried, they don't work.
Readme
This tool converts from CSV to Object arrays, or JSON. It can do TSV too. Here's a super basic example.
Install
npm i actual-csv-to-json-parser
Call Function
import { csvTextToObjectArray } from "actual-csv-to-json-parser";
const numbers = csvTextToObjectArray(`
name, num, even
ten, 10, TRUE
fifteen, 15, FALSE
`);
console.log(numbers[0]) // --> { name: "ten", num: 10, even: true }
console.log(numbers[1]) // --> { name: "fifteen", num: 15, even: false }
--alternatively--
import { csvFileToObjectArraySync } from "actual-csv-to-json-parser";
import * as pathTool from "path";
const csvLoadPath = pathTool.join(__dirname, "/path/to/file.csv");
const items = csvFileToObjectArraySync(csvLoadPath);
items.forEach((item) => console.log(item));
--or as an extreme example--
import { CsvParser } from "actual-csv-to-json-parser";
import * as pathTool from "path";
const csvLoadPath = pathTool.join(__dirname, "/path/to/file.csv");
const jsonSavePath = pathTool.join(__dirname, "/path/to/output.json");
// all the bells and whistles
const parser = new CsvParser({
delimiter: /,/, // default
jsonTabSize: 2, // default
trimRawText: true, // default
convertPrimitives: ["boolean", "number", "array", "object"], // default
});
// load a csv file, modify it, save it as json
parser.convertFileToJsonFileSync<{name: string, age: number}>(csvLoadPath, jsonSavePath, (items) => {
items.forEach((item) => item.age += 1);
return items;
})
See "Overview of Functions" for more
If you want a typescript interface of your json object, check out this tool: http://json2ts.com/
More later, but this is the basics of what exists
Default quick functions
csvTextToObjectArray(rawCsvText)
async csvFileToObjectArray(csvFilePath)
csvFileToObjectArraySync(csvFilePath)
csvTextTo2dArray(rawCsvText)
async csvFileTo2dArray(csvFilePath)
csvFileTo2dArraySync(csvFilePath)
csvTextToJsonText(rawCsvText)
async csvFileToJsonFile(csvFilePath, jsonSavePath)
csvFileToJsonFileSync(csvFilePath, jsonSavePath)
Custom specialty stuff. Same as above but with customized csv parser args
new CsvParser(customizationArgs)
this.rawTextTo2dArray(rawCsvText)
this.fileTo2dArray(csvFilePath)
this.fileTo2dArraySync(csvFilePath)
this.rawTextToObjectArray(rawCsvText)
this.fileToObjectArray(csvFilePath)
this.fileToObjectArraySync(csvFilePath)
this.rawTextToJsonText(rawCsvText)
this.convertFileToJsonFile(csvFilePath, jsonSavePath)
this.convertFileToJsonFileSync(csvFilePath, jsonSavePath)
This is a CSV (Comma Separated Values):
name, age, eyesight
bob, 21, 20/20
julie, 27, 21/19
mark, 42, 17/17
This is an 2D String Array
const peeps = [
[ "name", "age", "eyesight" ],
[ "bob", "21", "20/20" ],
[ "julie", "27", "21/19" ],
[ "mark", "42", "17/17" ],
]
This is an object array (probably what you want)
const peeps = [
{ name: "bob", age: "21", eyesight: "20/20"},
{ name: "julie", age: "27", eyesight: "21/19"},
{ name: "mark", age: "42", eyesight: "17/17"},
]
This is json (JSON is a string)
const json = `[
{
"name": "bob",
"age": "21",
"eyesight": "20/20"
},
{
"name": "julie",
"age": "27",
"eyesight": "21/19"
},
{
"name": "mark",
"age": "42",
"eyesight": "17/17"
},
]`
This data is used in the examples below
// imagine raw text also found at /path/to/file.csv
const EXAMPLE_DATA = `
a, b
1, 2
x, y
`;
interface IExampleData {
a: string;
b: string;
}
Creating Object Arrays
csvTextToObjectArray(rawCsvText: string)
Creates an object array from csv. Most useful function, likely. The IExampleData
templating is optional.
const items = csvTextToObjectArray<IExampleData>(EXAMPLE_DATA);
/* items === [
{a: "1", b: "2"},
{a: "x", b: "y"}
]*/
csvFileToObjectArray(csvFilePath: string)
Asynchronously load a file, turn it into an array of objects. The IExampleData
templating is optional.
const csvLoadPath = path.join(__dirname, "/path/to/file.csv");
csvFileToObjectArray<IExampleData>(csvLoadPath).then((items) => console.log(items));
// or
const items = await csvFileToObjectArray<IExampleData>(csvLoadPath);
csvFileToObjectArraySync(csvFilePath: string)
Synchronously load a file, turn it into an array of objects. The IExampleData
templating is optional.
const csvLoadPath = path.join(__dirname, "/path/to/file.csv");
const items = csvFileToObjectArraySync<IExampleData>(csvLoadPath);
Creating 2D String Arrays
csvTextTo2dArray(rawCsvText: string)
Creates a 2d array from raw csv text
const array2d = csvTextTo2dArray(EXAMPLE_DATA);
/* array2d === [
["a", "b"],
["1", "2"],
["x", "y"],
]*/
csvFileTo2dArray(csvFilePath: string)
Asynchronously creates a 2d array from a csv file
const csvLoadPath = path.join(__dirname, "/path/to/file.csv");
csvFileTo2dArray(csvLoadPath).then((array2d) => console.log(array2d));
// or
const array2d = await csvFileTo2dArray(csvLoadPath);
csvFileTo2dArraySync(csvFilePath: string)
Synchronously creates a 2d array from a csv file
const csvLoadPath = path.join(__dirname, "/path/to/file.csv");
const array2d = csvFileTo2dArraySync(csvLoadPath);
Creating JSON string
csvTextToJsonText(rawCsvText: string)
Turn raw csv text into json text
const json = csvTextToJsonText(EXAMPLE_DATA);
/* json === `[
{"a": "1", "b": "2"},
{"a": "x", "b": "y"}
]`*/
Direct conversion from .csv to .json files
csvFileToJsonFile(csvFilePath: string, jsonSavePath: string)
Asynchronously load a file, convert it to json, then save it. The IExampleData
templating is optional.
(optional). You can add a function to parse the object array before saving it
const csvLoadPath = path.join(__dirname, "/path/to/file.csv");
const jsonSavePath = path.join(__dirname, "/path/to/output.json")
csvFileToJsonFile(csvLoadPath, jsonSavePath).then(() => console.log("File saved"))
// or (with conversion)
await csvFileToJsonFile<IExampleData>(csvLoadPath, jsonSavePath, (items) => {
items.forEach((it) => it.b = "foo");
return items;
});
csvFileToJsonFileSync(csvFilePath: string, jsonSavePath: string)
Synchronously load a file, convert it to json, then save it. The IExampleData
templating is optional.
(optional). You can add a function to parse the object array before saving it
const csvLoadPath = path.join(__dirname, "/path/to/file.csv");
const jsonSavePath = path.join(__dirname, "/path/to/output.json")
csvFileToJsonFileSync(csvLoadPath, jsonSavePath);
// or (with conversion)
csvFileToJsonFileSync<IExampleData>(csvLoadPath, jsonSavePath, (items) => {
items.forEach((it) => it.b = "foo");
return items;
});
Special Cases
ICsvParserArgs
All the special setting for the parser.
interface ICsvParserArgs {
delimiter?: RegExp | string;
jsonTabSize?: null | number;
trimRawText?: boolean;
convertPrimitives?: boolean | Array<"boolean" | "number" | "array" | "object">,
}
new CsvParser(args: ICsvParserArgs)
Create a special csv parser, with custom rules
const parser = new CsvParser({
delimeter: "\t", // now does TSV
jsonTabSize: 3, // set to null for one-liner json
});
const array2d = parser.fileTo2dArraySync("/path/to/file.csv");
Search for CsvParser()
. It has a delimiter argument.
const testText = `
a,b,c
1,2,3
"list, of, things","a ""tough, ugly, quote""",thing
TRUE,bar,qux
"[1, 2, 3]","{""first"": 1}",false
`
test(`Doesn't break on quotes or commas. Handles primitives and json.`, async (t) => {
const array2d = csvTextTo2dArray(testText);
t.deepEqual(array2d, [
["a", "b", "c"],
[1, 2, 3],
["list, of, things", `a "tough, ugly, quote"`, `thing`],
[true, "bar", `qux`],
[[1,2,3], {first: 1}, false],
])
})
This isn't so much a rant, I'm just going to say I didn't much like the other csv tools. Here's the best two I could find:
Then there's like 100 more.
FAQs
Don't waste time with the other csv to json parsers. I tried, they don't work.
The npm package actual-csv-to-json-parser receives a total of 6 weekly downloads. As such, actual-csv-to-json-parser popularity was classified as not popular.
We found that actual-csv-to-json-parser demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.
Security News
UnitedHealth Group disclosed that the ransomware attack on Change Healthcare compromised protected health information for millions in the U.S., with estimated costs to the company expected to reach $1 billion.