{"id":13412618,"url":"https://github.com/mrodrig/json-2-csv","last_synced_at":"2025-05-14T03:07:14.422Z","repository":{"id":16249412,"uuid":"18997270","full_name":"mrodrig/json-2-csv","owner":"mrodrig","description":"Convert JSON to CSV *or* CSV to JSON!","archived":false,"fork":false,"pushed_at":"2025-03-06T03:49:04.000Z","size":1001,"stargazers_count":441,"open_issues_count":6,"forks_count":58,"subscribers_count":7,"default_branch":"main","last_synced_at":"2025-05-05T20:50:59.926Z","etag":null,"topics":["cli","csv","csv2json","hacktoberfest","javascript","json","json2csv","node","node-module","rfc4180"],"latest_commit_sha":null,"homepage":"https://mrodrig.github.io/json-2-csv","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mrodrig.png","metadata":{"files":{"readme":"README.md","changelog":null,"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":"2014-04-21T15:48:50.000Z","updated_at":"2025-04-28T08:31:07.000Z","dependencies_parsed_at":"2023-01-13T18:46:00.119Z","dependency_job_id":"945b3d33-2ab2-4972-a95b-0e6a6e64fa40","html_url":"https://github.com/mrodrig/json-2-csv","commit_stats":{"total_commits":343,"total_committers":26,"mean_commits":"13.192307692307692","dds":"0.49271137026239065","last_synced_commit":"95511409c746a9f38b67134990514a6f8a31a61f"},"previous_names":[],"tags_count":84,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrodrig%2Fjson-2-csv","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrodrig%2Fjson-2-csv/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrodrig%2Fjson-2-csv/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrodrig%2Fjson-2-csv/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mrodrig","download_url":"https://codeload.github.com/mrodrig/json-2-csv/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254059500,"owners_count":22007768,"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":["cli","csv","csv2json","hacktoberfest","javascript","json","json2csv","node","node-module","rfc4180"],"created_at":"2024-07-30T20:01:26.847Z","updated_at":"2025-05-14T03:07:14.382Z","avatar_url":"https://github.com/mrodrig.png","language":"TypeScript","readme":"# json-2-csv\n**Convert JSON to CSV _or_ CSV to JSON**\n\n[![NPM version](https://img.shields.io/npm/v/json-2-csv.svg)](https://www.npmjs.org/package/json-2-csv)\n[![Typings](https://img.shields.io/npm/types/json-2-csv)](https://www.npmjs.org/package/json-2-csv)\n[![Downloads](https://img.shields.io/npm/dm/json-2-csv.svg)](https://www.npmjs.org/package/json-2-csv)\n[![Minzipped Size](https://img.shields.io/bundlephobia/minzip/json-2-csv)](https://bundlephobia.com/result?p=json-2-csv)\n\n[![Build Status](https://img.shields.io/github/actions/workflow/status/mrodrig/json-2-csv/automated-tests-workflow.yml)](https://github.com/mrodrig/json-2-csv/actions/workflows/automated-tests-workflow.yml)\n[![Coverage Status](https://coveralls.io/repos/github/mrodrig/json-2-csv/badge.svg?branch=main)](https://coveralls.io/github/mrodrig/json-2-csv?branch=main)\n[![Maintainability](https://api.codeclimate.com/v1/badges/8c0cc3699d054fb77abe/maintainability)](https://codeclimate.com/github/mrodrig/json-2-csv/maintainability)\n\nThis node module will convert an array of JSON documents to a CSV string.\nColumn headings will be automatically generated based on the keys of the JSON documents. Nested documents will have a '.' appended between the keys.\n\nIt is also capable of converting CSV of the same form back into the original array of JSON documents.\nThe columns headings will be used as the JSON document keys.  All lines must have the same exact number of CSV values.\n\n## Installation\n\n```bash\n$ npm install json-2-csv\n```\n\nCLI:\n```bash\n$ npm install @mrodrig/json-2-csv-cli\n```\n\n## Upgrading?\n\nUpgrading to v5 from v4? Check out the [upgrade guide](https://github.com/mrodrig/json-2-csv/blob/master/upgrade_guides/UPGRADE_4_to_5.md).\n\n## Usage\n\n```javascript\nlet converter = require('json-2-csv');\nconst csv = await converter.json2csv(data, options);\n```\nor\n```javascript\nimport { json2csv } from 'json-2-csv';\n```\n\n### API\n\n#### `json2csv(array, options)` =\u003e `string`\n\nReturns the CSV `string` or rejects with an `Error` if there was an issue.\n\n* `array` - An array of JSON documents to be converted to CSV.\n* `options` - (Optional) A JSON document specifying any of the following key value pairs:\n  * `arrayIndexesAsKeys` - Boolean - Should array indexes be included in the generated keys?\n    * Default: `false`\n    * Note: This provides a more accurate representation of the JSON in the returned CSV, but may be less human readable. See [#207](https://github.com/mrodrig/json-2-csv/issues/207) for more details.\n  * `checkSchemaDifferences` - Boolean - Should all documents have the same schema?\n    * Default: `false`\n    * Note: An error will be thrown if some documents have differing schemas when this is set to `true`.\n  * `delimiter` - Document - Specifies the different types of delimiters\n    * `field` - String - Field Delimiter. \n      * Default: `,`\n    * `wrap` - String - Wrap values in the delimiter of choice (e.g. wrap values in quotes). \n      * Default: `\"`\n    * `eol` - String - End of Line Delimiter. \n      * Default: `\\n`\n  * `emptyFieldValue` - Any - Value that, if specified, will be substituted in for field values that are `undefined`, `null`, or an empty string.\n    * Default: none\n  * `escapeHeaderNestedDots` - Boolean - Should nested dots in header keys be escaped?\n    * Default: `true`\n    * Example:\n    ```json\n    [\n      {\n        \"a.a\": \"1\"\n      }\n    ]\n    ```\n      * `true` will generate the following CSV:\n      ```csv\n      a\\.a\n      1\n      ```\n      * `false` will generate the following CSV:\n      ```csv\n      a.a\n      1\n      ```\n    * Note: This may result in CSV output that does not map back exactly to the original JSON.\n  * `excelBOM` - Boolean - Should a unicode character be prepended to allow Excel to open a UTF-8 encoded file with non-ASCII characters present.\n  * `excludeKeys` - Array - Specify the `string` keys or `RegExp` patterns that should be excluded from the output. Provided `string` keys will also be used as a RegExp to help exclude keys under a specified prefix, such as all keys of Objects in an Array when `expandArrayObjects` is `true` (e.g., providing `'baz'` will exclude `'baz.a'` too).\n    * Default: `[]`\n    * Note: When used with `unwindArrays`, arrays present at excluded key paths will not be unwound.\n  * `expandNestedObjects` - Boolean - Should nested objects be deep-converted to CSV?\n  \t* Default: `true`\n  \t* Example:\n\t```json\n\t[\n\t\t{\n      \"make\": \"Nissan\",\n      \"model\": \"Murano\",\n      \"year\": 2013,\n      \"specifications\": {\n        \"mileage\": 7106,\n        \"trim\": \"S AWD\"\n      }\n    }\n\t]\n\t```\n  \t* `true` uses the following keys:\n  \t\t* `['make', 'model', 'year', 'specifications.mileage', 'specifications.trim']`\n  \t* `false` uses the following keys:\n  \t\t* `['make', 'model', 'year', 'specifications']`\n    * Note: This may result in CSV output that does not map back exactly to the original JSON.\n  * `expandArrayObjects` - Boolean - Should objects in array values be deep-converted to CSV?\n  \t* Default: `false`\n  \t* Example:\n\t```json\n\t[\n\t\t{ \n\t\t\t\"specifications\": [\n\t\t\t\t{ \"features\": [...] },\n\t\t\t\t{ \"mileage\": \"5000\" }\n\t\t\t]\n\t\t}\n\t]\n\t```\n  \t* `true` uses the following keys:\n  \t\t* `['specifications.features', 'specifications.mileage']`\n  \t* `false` uses the following keys:\n  \t\t* `['specifications']`\n    * Note: This may result in CSV output that does not map back exactly to the original JSON. See #102 for more information.\n  * `keys` - Array - Specify the keys that should be converted.\n    * Default: These will be auto-detected from your data by default.\n    * Keys can either be specified as a String representing the key path that should be converted, or as an Object of the following format:\n    ```javascript\n    {\n      \"field\": \"string\", // required\n      \"title\": \"string\", // optional\n      \"wildcardMatch\": false, // optional - default: false\n    }\n    ```\n      * When specifying keys as an Object, the `field` property specifies the key path, while `title` specifies a more human readable field heading. Additionally, the `wildcardMatch` option allows you to optionally specify that all auto-detected fields with the specified field prefix should be included in the CSV. The list specified can contain a combination of Objects and Strings.\n      * Examples:\n        * `[ 'key1', 'key2', ... ]`\n        * `[ 'key1', { field: 'key2', wildcardMatch: true }]`\n        * `[ { field: 'key1', title: 'Key 1' }, { field: 'key2' }, 'key3', ... ]`\n    * Key Paths - If you are converting a nested object (ie. {info : {name: 'Mike'}}), then set this to ['info.name']\n  * `parseValue` - Function - Specify how values should be converted into CSV format. This function is provided a single field value at a time and must return a `String`. The built-in parsing method is provided as the second argument for cases where default parsing is preferred.\n    * Default: A built-in method is used to parse out a variety of different value types to well-known formats.\n    * Note: Using this option may override other options, including `useDateIso8601Format` and `useLocaleFormat`.\n  * `prependHeader` - Boolean - Should the auto-generated header be prepended as the first line in the CSV?\n    * Default: `true`\n  * `sortHeader` - Boolean or Function - Should the header keys be sorted in alphabetical order? or pass a function to use a custom sorting function\n    * Default: `false`\n  * `trimFieldValues` - Boolean - Should the field values be trimmed?\n    * Default: `false`\n  * `trimHeaderFields` - Boolean - Should the header fields be trimmed? \n    * Default: `false`\n  * `unwindArrays` - Boolean - Should array values be \"unwound\" such that there is one line per value in the array?\n      * Default: `false`\n      * Example:\n      ```json\n      [\n          {\n              \"_id\": {\"$oid\": \"5cf7ca3616c91100018844af\"},\n              \"data\": {\"category\": \"Computers\", \"options\": [{\"name\": \"MacBook Pro 15\"}, {\"name\": \"MacBook Air 13\"}]}\n          },\n          {\n              \"_id\": {\"$oid\": \"5cf7ca3616c91100018844bf\"},\n              \"data\": {\"category\": \"Cars\", \"options\": [{\"name\": \"Supercharger\"}, {\"name\": \"Turbocharger\"}]}\n          }\n      ]\n      ```\n      * `true` will unwind the JSON to four objects, and therefore four lines of CSV values:\n      ```csv\n      _id.$oid,data.category,data.options.name\n      5cf7ca3616c91100018844af,Computers,MacBook Pro 15\n      5cf7ca3616c91100018844af,Computers,MacBook Air 13\n      5cf7ca3616c91100018844bf,Cars,Supercharger\n      5cf7ca3616c91100018844bf,Cars,Turbocharger\n      ```\n      * `false` will leave the values unwound and will convert the array as-is (when this option is used without expandArrayObjects):\n      ```csv\n      _id.$oid,data.category,data.options\n      5cf7ca3616c91100018844af,Computers,\"[{\"\"name\"\":\"\"MacBook Pro 15\"\"},{\"\"name\"\":\"\"MacBook Air 13\"\"}]\"\n      5cf7ca3616c91100018844bf,Cars,\"[{\"\"name\"\":\"\"Supercharger\"\"},{\"\"name\"\":\"\"Turbocharger\"\"}]\"\n      ```\n  \t* Note: This may result in CSV output that does not map back exactly to the original JSON.\n  * `useDateIso8601Format` - Boolean - Should date values be converted to an ISO8601 date string?\n    * Default: `false`\n    * Note: If selected, values will be converted using `toISOString()` rather than `toString()` or `toLocaleString()` depending on the other options provided.\n  * `useLocaleFormat` - Boolean - Should values be converted to a locale specific string?\n    * Default: `false`\n    * Note: If selected, values will be converted using `toLocaleString()` rather than `toString()`\n  * `wrapBooleans` - Boolean - Should boolean values be wrapped in wrap delimiters to prevent Excel from converting them to Excel's TRUE/FALSE Boolean values.\n    * Default: `false`\n  * `preventCsvInjection` - Boolean - Should CSV injection be prevented by left trimming these characters: Equals (=), Plus (+), Minus (-), At (@), Tab (0x09), Carriage return (0x0D).\n    * Default: `false`\n\n\n#### `csv2json(csv, options)` =\u003e object[]\n\nReturns the JSON object array (`object[]`) or rejects with an `Error` if there was an issue.\n\n* `csv` - A string of CSV\n* `options` - (Optional) A JSON document specifying any of the following key value pairs:\n  * `delimiter` - Document - Specifies the different types of delimiters\n    * `field` - String - Field Delimiter. \n      * Default: `,`\n    * `wrap` - String - The character that field values are wrapped in. \n      * Default: `\"`\n    * `eol` - String - End of Line Delimiter. \n      * Default: `\\n`\n  * `excelBOM` - Boolean - Does the CSV contain a unicode character prepended in order to allow Excel to open a UTF-8 encoded file with non-ASCII characters present?\n    * Default: `false`\n  * `headerFields` - Array - Specify the field names (as strings) in place of a header line in the CSV itself.\n    * Default: Parses the header fields directly from the CSV string\n    * If you want to generate a nested object (ie. `{info : {name: 'Mike'}}`), then use `.` characters in the string to denote a nested field, like ['info.name']\n    * If your CSV has a header line included, then don't specify the option to utilize the default values that will be parsed from the CSV.\n  * `keys` - Array - Specify the keys (as strings) that should be converted. \n    * Default: `null`\n    * If you have a nested object (ie. `{info : {name: 'Mike'}}`), then set this to `['info.name']`\n    * If you want all keys to be converted, then specify `null` or don't specify the option to utilize the default.\n  * `parseValue` - Function - Specify how `String` representations of field values should be parsed when converting back to JSON. This function is provided a single `String` and can return any value.\n    * Default: `JSON.parse` - An attempt is made to convert the String back to its original value using `JSON.parse`.\n  * `trimHeaderFields` - Boolean - Should the header fields be trimmed? \n    * Default: `false`\n  * `trimFieldValues` - Boolean - Should the field values be trimmed? \n    * Default: `false`\n\n### CLI\nNote: As of `3.5.8`, the command line interface functionality has been pulled out to a separate package. Please be sure to\ninstall the `@mrodrig/json-2-csv-cli` NPM package if you wish to use the CLI functionality shown below:\n\n```bash\n$ npm install @mrodrig/json-2-csv-cli\n``` \n\n#### json2csv\n```\nUsage: json2csv \u003cjsonFile\u003e [options]\n\nArguments:\n  jsonFile                         JSON file to convert\n\nOptions:\n  -V, --version                    output the version number\n  -o, --output [output]            Path of output file. If not provided, then stdout will be used\n  -a, --array-indexes-as-keys      Includes array indexes in the generated keys\n  -S, --check-schema               Check for schema differences\n  -f, --field \u003cdelimiter\u003e          Field delimiter\n  -w, --wrap \u003cdelimiter\u003e           Wrap delimiter\n  -e, --eol \u003cdelimiter\u003e            End of Line delimiter\n  -E, --empty-field-value \u003cvalue\u003e  Empty field value\n  -n, --expand-nested-objects      Expand nested objects to be deep converted to CSV\n  -k, --keys [keys]                Keys of documents to convert to CSV\n  -d, --escape-header-nested-dots  Escape header nested dots\n  -b, --excel-bom                  Excel Byte Order Mark character prepended to CSV\n  -x, --exclude-keys [keys]        Comma separated list of keys to exclude\n  -A, --expand-array-objects       Expand array objects\n  -W, --without-header             Withhold the prepended header\n  -p, --prevent-csv-injection      Prevent CSV Injection\n  -s, --sort-header                Sort the header fields\n  -F, --trim-fields                Trim field values\n  -H, --trim-header                Trim header fields\n  -U, --unwind-arrays              Unwind array values to their own CSV line\n  -I, --iso-date-format            Use ISO 8601 date format\n  -L, --locale-format              Use locale format for values\n  -B, --wrap-booleans              Wrap booleans\n  -h, --help                       display help for command\n```\n\n#### csv2json\n```\nUsage: csv2json \u003ccsvFile\u003e [options]\n\nArguments:\n  csvFile                      CSV file to convert\n\nOptions:\n  -V, --version                output the version number\n  -o, --output [output]        Path of output file. If not provided, then stdout will be used\n  -f, --field \u003cdelimiter\u003e      Field delimiter\n  -w, --wrap \u003cdelimiter\u003e       Wrap delimiter\n  -e, --eol \u003cdelimiter\u003e        End of Line delimiter\n  -b, --excel-bom              Excel Byte Order Mark character prepended to CSV\n  -p, --prevent-csv-injection  Prevent CSV Injection\n  -F, --trim-fields            Trim field values\n  -H, --trim-header            Trim header fields\n  -h, --header-fields          Specify the fields names in place a header line in the CSV itself\n  -k, --keys [keys]            Keys of documents to convert to CSV\n  --help                       display help for command\n```\n\n## Tests\n\n```bash\n$ npm test\n```\n\nTo see test coverage, please run:\n```bash\n$ npm run coverage\n```\n\n## Features\n* Header Generation (per document keys)\n* Allows for conversion of specific keys in both json2csv and csv2json via the options.keys parameter (as of 1.1.2)\n* Document schema verification functionality (field order is irrelevant) (as of 1.1.0)\n* Supports sub-documents natively\n* Supports arrays as document values for both json2csv and csv2json\n* Custom ordering of columns (see F.A.Q. for more information)\n* Ability to re-generate the JSON documents that were used to generate the CSV (including nested documents)\n* Allows for custom field delimiters, end of line delimiters, etc.\n* Wrapped value support for json2csv and csv2json (as of 1.3.0)\n* Support for multiple different schemas (as of 1.4.0)\n* RFC 4180 Compliance (as of 3.0.0)\n* CLI functionality (as of 3.0.0)\n\t* `csv2json test.csv -o output.json`\n\t* *and*\n\t* `json2csv test.json -o output.csv -W -k arrayOfStrings -o output.csv`\n* Empty field value option (as of 3.1.0)\n* TypeScript typings included (as of 3.4.0) - thanks to [@GabrielCastro](https://github.com/GabrielCastro)!\n* Synchronous use case support (as of 5.0.0) - thanks to [@Nokel81](https://github.com/Nokel81)","funding_links":[],"categories":["TypeScript","JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmrodrig%2Fjson-2-csv","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmrodrig%2Fjson-2-csv","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmrodrig%2Fjson-2-csv/lists"}