{"id":16716400,"url":"https://github.com/josdejong/csv42","last_synced_at":"2025-04-13T05:24:22.110Z","repository":{"id":66008763,"uuid":"602535075","full_name":"josdejong/csv42","owner":"josdejong","description":"A small and fast CSV parser with support for nested JSON","archived":false,"fork":false,"pushed_at":"2023-09-14T07:35:22.000Z","size":668,"stargazers_count":100,"open_issues_count":0,"forks_count":6,"subscribers_count":4,"default_branch":"main","last_synced_at":"2024-05-02T05:32:45.189Z","etag":null,"topics":["csv","csv-parser","json"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"isc","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/josdejong.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-16T12:21:47.000Z","updated_at":"2024-06-21T12:56:05.100Z","dependencies_parsed_at":null,"dependency_job_id":"e550673a-baa6-40cd-88b3-0386c5d14e18","html_url":"https://github.com/josdejong/csv42","commit_stats":{"total_commits":117,"total_committers":1,"mean_commits":117.0,"dds":0.0,"last_synced_commit":"55311ca594235ed61b264e2b88ebf1bac58c8579"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/josdejong%2Fcsv42","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/josdejong%2Fcsv42/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/josdejong%2Fcsv42/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/josdejong%2Fcsv42/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/josdejong","download_url":"https://codeload.github.com/josdejong/csv42/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248666931,"owners_count":21142345,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csv","csv-parser","json"],"created_at":"2024-10-12T21:13:18.228Z","updated_at":"2025-04-13T05:24:22.083Z","avatar_url":"https://github.com/josdejong.png","language":"TypeScript","funding_links":["https://github.com/sponsors/josdejong","https://github.com/sponsors/josdejong)."],"categories":[],"sub_categories":[],"readme":"# csv42\n\nA small and fast CSV parser with support for nested JSON.\n\n[![Version](https://img.shields.io/npm/v/csv42.svg)](https://www.npmjs.com/package/csv42)\n[![Downloads](https://img.shields.io/npm/dm/csv42.svg)](https://www.npmjs.com/package/csv42)\n[![Build Status](https://github.com/josdejong/csv42/workflows/Node.js%20CI/badge.svg)](https://github.com/josdejong/csv42/actions)\n[![Maintenance](https://img.shields.io/maintenance/yes/2024.svg)](https://github.com/josdejong/csv42/graphs/commit-activity)\n[![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://github.com/josdejong/csv42/blob/main/LICENSE.md)\n[![Codecov](https://codecov.io/gh/josdejong/csv42/branch/main/graph/badge.svg)](https://codecov.io/gh/josdejong/csv42)\n[![Github Sponsor](https://img.shields.io/github/sponsors/josdejong)](https://github.com/sponsors/josdejong)\n\n## Features\n\n- **2 way**: convert JSON to CSV and the other way around.\n- **Simple**: straightforward and flexible API.\n- **Lightweight**: 2KB gzipped with everything included, 1KB gzipped when only using `json2csv`.\n- **Fast**: faster than the popular CSV libraries out there. See [benchmark](https://jsoneditoronline.org/indepth/parse/csv-parser-javascript/).\n- **Safe**: handles inhomogeneous data, no risk of data loss.\n- **Modular**: only load what you use, thanks to ES5 modules and a plugin architecture.\n- **Powerful**:\n  - Configurable properties: `header`, `delimiter`, `eol`.\n  - Configurable `fields`, with custom value getters and setters and the ability to ignore fields.\n  - Configurable serialization and deserialization of values via `formatValue` and `parseValue`.\n  - Support for nested JSON objects: either flatten nested contents, or stringify as a JSON object.\n- **Standards compliant**: adheres to the CSV standard [RFC 4180](https://datatracker.ietf.org/doc/html/rfc4180).\n- **Universal**: Created for the browser, but can be used in any JavaScript environment like node.js. TypeScript types included.\n\nNote that the parser has no streaming support.\n\n## Why?\n\nWell, you have to write a CSV parser at least once in you life, right? ;)\n\nThe `csv42` library was developed specifically for https://jsoneditoronline.org, for use in the browser. Besides being small and fast, one important feature is supporting nested JSON objects. So, why the name `csv42`? Just because [42](\u003chttps://simple.wikipedia.org/wiki/42_(answer)\u003e) is a beautiful number and to remind us that there is a whole universe of beautiful CSV libraries out there.\n\n## Install\n\n```\nnpm install csv42\n```\n\n## Usage\n\nInstall the library once:\n\n### Convert JSON to CSV\n\n```ts\nimport { json2csv } from 'csv42'\n\nconst users = [\n  { id: 1, name: 'Joe', address: { city: 'New York', street: '1st Ave' } },\n  { id: 2, name: 'Sarah', address: { city: 'Manhattan', street: 'Spring street' } }\n]\n\n// By default, nested JSON properties are flattened\nconst csv = json2csv(users)\nconsole.log(csv)\n// id,name,address.city,address.street\n// 1,Joe,New York,1st Ave\n// 2,Sarah,Manhattan,Spring street\n\n// You can turn off flattening using the option `flatten`\nconst csvFlat = json2csv(users, { flatten: false })\nconsole.log(csvFlat)\n// id,name,address\n// 1,Joe,\"{\"\"city\"\":\"\"New York\"\",\"\"street\"\":\"\"1st Ave\"\"}\"\n// 2,Sarah,\"{\"\"city\"\":\"\"Manhattan\"\",\"\"street\"\":\"\"Spring street\"\"}\"\n\n// The CSV output can be fully customized and transformed using `fields`:\nconst csvCustom = json2csv(users, {\n  fields: [\n    { name: 'name', getValue: (item) =\u003e item.name },\n    { name: 'address', getValue: (item) =\u003e item.address.city + ' - ' + object.address.street }\n  ]\n})\nconsole.log(csvCustom)\n// name,address\n// Joe,New York - 1st Ave\n// Sarah,Manhattan - Spring street\n```\n\n### Convert CSV to JSON\n\n```ts\nimport { csv2json } from 'csv42'\n\nconst csv = `id,name,address.city,address.street\n1,Joe,New York,1st Ave\n2,Sarah,Manhattan,Spring street`\n\n// By default, fields containing a dot will be parsed inty nested JSON objects\nconst users = csv2json(csv)\nconsole.log(users)\n// [\n//   { id: 1, name: 'Joe', address: { city: 'New York', street: '1st Ave' } },\n//   { id: 2, name: 'Sarah', address: { city: 'Manhattan', street: 'Spring street' } }\n// ]\n\n// Creating nested objects can be turned off using the option `nested`\nconst usersFlat = csv2json(csv, { nested: false })\nconsole.log(usersFlat)\n// [\n//   { id: 1, name: 'Joe', 'address.city': 'New York', 'address.street': '1st Ave' },\n//   { id: 2, name: 'Sarah', 'address.city': 'Manhattan', 'address.street': 'Spring street' }\n// ]\n\n// The JSON output can be customized using `fields`\nconst usersCustom = csv2json(csv, {\n  fields: [\n    { name: 'name', setValue: (item, value) =\u003e (item.name = value) },\n    { name: 'address.city', setValue: (item, value) =\u003e (item.city = value) }\n  ]\n})\nconsole.log(usersCustom)\n// [\n//   { name: 'Joe', city: 'New York' },\n//   { name: 'Sarah', city: 'Manhattan' }\n// ]\n```\n\n## API\n\n### `json2csv\u003cT\u003e(json: T[], options?: CsvOptions\u003cT\u003e) : string`\n\nWhere `options` is an object with the following properties:\n\n| Option        | Type                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |\n| ------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `header`      | `boolean`                                  | If true, a header will be created as first line of the CSV.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |\n| `delimiter`   | `string`                                   | Default delimiter is `,`. A delimiter must be a single character.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |\n| `eol`         | `\\r\\n` or `\\n`                             | End of line, can be `\\r\\n` (default) or `\\n`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |\n| `flatten`     | `boolean` or `(value: unknown) =\u003e boolean` | If `true` (default), plain, nested objects will be flattened in multiple CSV columns, and arrays and classes will be serialized in a single field. When `false`, nested objects will be serialized as JSON in a single CSV field. This behavior can be customized by providing your own callback function for `flatten`. For example, to flatten objects and arrays, you can use `json2csv(json, { flatten: isObjectOrArray })`, and to flatten a specific class, you can use `json2csv(json, { flatten: value =\u003e isObject(value) \\|\\| isCustomClass(value) })`. The option `flatten`is not applicable when`fields` is defined. |\n| `fields`      | `CsvField\u003cT\u003e[]` or `CsvFieldsParser\u003cT\u003e`    | A list with fields to be put into the CSV file. This allows specifying the order of the fields and which fields to include/excluded.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |\n| `formatValue` | `ValueFormatter`                           | Function used to change any type of value into a serialized string for the CSV. The build in formatter will only enclose values in quotes when necessary, and will stringify nested JSON objects.                                                                                                                                                                                                                                                                                                                                                                                                                               |\n\nA simple example of a `ValueFormatter` is the following. This formatter will enclose every value in quotes:\n\n```ts\nfunction formatValue(value: unknown): string {\n  return '\"' + String(value) + '\"'\n}\n```\n\n### `csv2json\u003cT\u003e(csv: string, options?: JsonOptions) : T[]`\n\nWhere `options` is an object with the following properties:\n\n| Option       | Type                                | Description                                                                                                                                                                                                                                                                                                              |\n| ------------ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `header`     | `boolean`                           | Should be set `true` when the first line of the CSV file contains a header                                                                                                                                                                                                                                               |\n| `delimiter`  | `string`                            | Default delimiter is `,`. A delimiter must be a single character.                                                                                                                                                                                                                                                        |\n| `nested`     | `boolean`                           | If `true` (default), field names containing a dot will be parsed into nested JSON objects. The option `nested` is not applicable when `fields` is defined.                                                                                                                                                               |\n| `fields`     | `JsonField[]` or `JsonFieldsParser` | A list with fields to be extracted from the CSV file into JSON. This allows specifying which fields are include/excluded, and how they will be put into the JSON object. A field can be specified either by name, like `{ name, setValue }`, or by the index of the columns in the CSV file, like `{ index, setValue }`. |\n| `parseValue` | `ValueParser`                       | Used to parse a stringified value into a value again (number, boolean, string, ...). The build in parser will parse numbers and booleans, and will parse stringified JSON objects.                                                                                                                                       |\n\nA simple value parser can look as follows, parsing numeric values into numbers. This will keep all values as string:\n\n```ts\nfunction parseValue(value: string, quoted: boolean): unknown {\n  const num = Number(value)\n  return isNaN(num) ? value : num\n}\n```\n\n### Utility functions\n\nThe library exports a number of utility functions:\n\n| Function                                                                | Description                                                                                                                                                                     |\n| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `createFormatValue(delimiter: string): (value: unknown) =\u003e string`      | Create a function that can format (stringify) a value into a valid CSV value, escaping the value when needed. This function is used as default for the option `formatValue`.    |\n| `parseValue(value: string): unknown`                                    | Parse a string into a value, parse numbers into a number, etc. This is the function used by default for the option `parseValue`.                                                |\n| `collectNestedPaths(records: NestedObject[], recurse: boolean): Path[]` | Loop over the data and collect all nested paths. This can be used to generate a list with fields.                                                                               |\n| `parsePath(pathStr: string): Path`                                      | Parse a path like `'items[3].name'`                                                                                                                                             |\n| `stringifyPath(path: Path): string`                                     | Stringify a path into a string like `'items[3].name'`                                                                                                                           |\n| `getIn(object: NestedObject, path: Path): unknown`                      | Get a nested property from an object                                                                                                                                            |\n| `setIn(object: NestedObject, path: Path, value: unknown): NestedObject` | Set a nested property in an object                                                                                                                                              |\n| `isObject(value: unknown): boolean`                                     | Returns true when `value` is a plain JavaScript object, and returns false for primitive values, arrays, and classes. Can be used as callback function for the option `flatten`. |\n| `isObjectOrArray(value: unknown): boolean`                              | Returns true when `value` is a plain JavaScript object or array, and returns false for primitive values and classes. Can be used as callback function for the option `flatten`. |\n\n## Alternatives\n\n- https://www.npmjs.com/package/csv\n- https://juanjodiaz.github.io/json2csv/\n- https://www.npmjs.com/package/json-2-csv\n- https://www.npmjs.com/package/papaparse\n- https://www.npmjs.com/package/csvtojson\n- https://www.npmjs.com/package/csv-stringify\n- https://www.npmjs.com/package/csv-parser\n- https://www.npmjs.com/package/fast-csv\n- https://github.com/leeoniya/uDSV/\n- Any many, many more...\n\n### Release\n\nTo release a new version:\n\n```\n$ npm run release\n```\n\nThis will:\n\n- lint\n- test\n- build\n- increment the version number\n- push the changes to git, add a git version tag\n- publish the npm package\n\nTo try the build and see the change list without actually publishing:\n\n```\n$ npm run release-dry-run\n```\n\n## License\n\n`csv42` is released as open source under the permissive the [ISC license](LICENSE.md).\n\n**If you are using `csv42` commercially, there is a _social_ (but no legal) expectation that you help fund its maintenance. [Start here](https://github.com/sponsors/josdejong).**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjosdejong%2Fcsv42","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjosdejong%2Fcsv42","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjosdejong%2Fcsv42/lists"}