{"name":"json2csv","version":"6.0.0-alpha.0","description":"Convert JSON to CSV","keywords":["json","to","csv","export","convert","parse"],"author":{"name":"Mirco Zeiss","email":"mirco.zeiss@gmail.com"},"license":"MIT","bin":{"json2csv":"bin/json2csv.js"},"main":"lib/json2csv.js","module":"dist/json2csv.esm.js","browser":"dist/json2csv.umd.js","repository":{"type":"git","url":"git+https://github.com/zemirco/json2csv.git"},"homepage":"http://zemirco.github.io/json2csv","scripts":{"build":"rollup -c","dev":"rollup -c -w","test":"node test | tap-spec","lint":"eslint bin lib test","test-with-coverage":"nyc --reporter=text node test | tap-spec","coveralls":"nyc report --reporter=text-lcov | coveralls","deploy:docs":"docpress b && gh-pages -d _docpress","prepublish":"in-publish && npm run before:publish || not-in-publish","before:publish":"npm test && npm run build","release":"standard-version"},"dependencies":{"commander":"^6.2.0","jsonparse":"^1.3.1","lodash.get":"^4.4.2"},"devDependencies":{"@babel/core":"^7.12.3","@babel/preset-env":"^7.12.1","coveralls":"^3.1.0","docpress":"^0.8.2","eslint":"^7.13.0","gh-pages":"^3.1.0","in-publish":"^2.0.1","nyc":"^15.1.0","rollup":"^2.33.2","rollup-plugin-babel":"^4.4.0","rollup-plugin-commonjs":"^10.1.0","rollup-plugin-node-polyfills":"^0.2.1","rollup-plugin-node-resolve":"^5.2.0","standard-version":"^9.0.0","tap-spec":"^5.0.0","tape":"^5.0.1"},"engines":{"node":">= 10","npm":">= 6.13.0"},"volta":{"node":"12.20.0"},"readme":"# json2csv\n\nConverts JSON into CSV with column titles and proper line endings.  \nCan be used as a module and from the command line.\n\n[![npm version][npm-badge]][npm-badge-url]\n[![Build Status][travis-badge]][travis-badge-url]\n[![Coverage Status][coveralls-badge]][coveralls-badge-url]\n\nSee the [CHANGELOG] for details about the latest release.\n\n> :construction: The documentation seen here is for the upcoming v6 which is a work in progress, see https://www.npmjs.com/package/json2csv for the documentation for the latest published version. See [v5 branch](https://github.com/zemirco/json2csv/tree/v5) for code for v5+.\n\nFeatures\n\n- Fast and lightweight\n- Scalable to infinitely large datasets (using stream processing)\n- Support for standard JSON as well as NDJSON\n- Advanced data selection (automatic field discovery, underscore-like selectors, custom data getters, default values for missing fields, transforms, etc.)\n- Highly customizable (supportting custom quotation marks, delimiters, eol values, etc.)\n- Automatic escaping (preserving new lines, quotes, etc. in them)\n- Optional headers\n- Unicode encoding support\n- Pretty printing in table format to stdout\n\n## How to install\n\nYou can install json2csv as a dependency using NPM.  \nRequires **Node v12** or higher.\n\n```sh\n# Global so it can be called from anywhere\n$ npm install -g json2csv\n# or as a dependency of a project\n$ npm install json2csv --save\n```\n\nAlso, if you are loading json2csv directly to the browser you can pull it directly from the CDN.\n\n```html\n<script src=\"https://cdn.jsdelivr.net/npm/json2csv\"></script>\n```\n\nBy default, the above script will get the latest release of json2csv. You can also specify a specific version:\n\n```html\n<script src=\"https://cdn.jsdelivr.net/npm/json2csv@4.2.1\"></script>\n```\n\n## Usage\n\n### Command Line Interface\n\n`json2csv` can be called from the command line if installed globally (using the `-g` flag).\n\n```bash\nUsage: json2csv [options]\n\nOptions:\n  -V, --version                       output the version number\n  -i, --input <input>                 Path and name of the incoming json file. Defaults to stdin.\n  -o, --output <output>               Path and name of the resulting csv file. Defaults to stdout.\n  -c, --config <path>                 Specify a file with a valid JSON configuration.\n  -n, --ndjson                        Treat the input as NewLine-Delimited JSON.\n  -s, --no-streaming                  Process the whole JSON array in memory instead of doing it line by line.\n  -f, --fields <fields>               List of fields to process. Defaults to field auto-detection.\n  -v, --default-value <defaultValue>  Default value to use for missing fields.\n  -q, --quote <quote>                 Character(s) to use as quote mark. Defaults to '\"'.\n  -Q, --escaped-quote <escapedQuote>  Character(s) to use as a escaped quote. Defaults to a double `quote`, '\"\"'.\n  -d, --delimiter <delimiter>         Character(s) to use as delimiter. Defaults to ','. (default: \",\")\n  -e, --eol <eol>                     Character(s) to use as End-of-Line for separating rows. Defaults to '\\n'. (default: \"\\n\")\n  -E, --excel-strings                 Wraps string data to force Excel to interpret it as string even if it contains a number.\n  -H, --no-header                     Disable the column name header.\n  -a, --include-empty-rows            Includes empty rows in the resulting CSV output.\n  -b, --with-bom                      Includes BOM character at the beginning of the CSV.\n  -p, --pretty                        Print output as a pretty table. Use only when printing to console.\n  --unwind [paths]                    Creates multiple rows from a single JSON document similar to MongoDB unwind.\n  --unwind-blank                      When unwinding, blank out instead of repeating data. Defaults to false. (default: false)\n  --flatten-objects                   Flatten nested objects. Defaults to false. (default: false)\n  --flatten-arrays                    Flatten nested arrays. Defaults to false. (default: false)\n  --flatten-separator <separator>     Flattened keys separator. Defaults to '.'. (default: \".\")\n  -h, --help                          output usage information\n```\n\nIf no input `-i` is specified the result is expected from to the console standard input.\nIf no output `-o` is specified the result is printed to the console standard output.\nIf no fields `-f` or config `-c` are passed the fields of the first element are used since json2csv CLI process the items one at a time. You can use the `--no-streaming` flag to load the entire JSON in memory and get all the headers. However, keep in mind that this is slower and requires much more memory.\nUse `-p` to show the result as a table in the console.\n\nAny option passed through the config file `-c` will be overriden if a specific flag is passed as well. For example, the fields option of the config will be overriden if the fields flag `-f` is used.\n\nFor more details, you can check some of our CLI usage [examples](./docs/cli-examples.md) or our [test suite](test/CLI.js).\n\n## Javascript module\n\n`json2csv` can also be use programatically from you javascript codebase.\n\nThe programatic APIs take a configuration object very similar to the CLI options. All APIs take the exact same options.\n\n- `fields` - Array of Objects/Strings. Defaults to toplevel JSON attributes. See example below.\n- `ndjson` - Boolean, indicates that the data is in NDJSON format. Only effective when using the streaming API and not in object mode.\n- `transforms` - Array of transforms. A transform is a function that receives a data recod and returns a transformed record. Transforms are executed in order before converting the data record into a CSV row. See bellow for more details.\n- `formatters` - Object where the each key is a Javascript data type and its associated value is a formatters for the given type. A formatter is a function that receives the raw js value of a given type and formats it as a valid CSV cell. Supported types are the types returned by `typeof` i.e. `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` and `object`.\n- `defaultValue` - Default value to use when missing data. Defaults to `<empty>` if not specified. (Overridden by `fields[].default`)\n- `delimiter` - String, delimiter of columns. Defaults to `,` if not specified.\n- `eol` - String, overrides the default OS line ending (i.e. `\\n` on Unix and `\\r\\n` on Windows).\n- `header` - Boolean, determines whether or not CSV file will contain a title column. Defaults to `true` if not specified.\n- `includeEmptyRows` - Boolean, includes empty rows. Defaults to `false`.\n- `withBOM` - Boolean, with BOM character. Defaults to `false`.\n\n### Transforms\n\njson2csv supports transforms. A transform is a function that receives a data record and returns a transformed record.\n\n#### Custom transforms\n\n```js\nfunction doNothing(item) {\n  // apply tranformations or create new object\n  return transformedItem;\n}\n```\n\nor using ES6\n\n```js\nconst doNothing = (item) => {\n  // apply tranformations or create new object\n  return transformedItem;\n};\n```\n\nFor example, let's add a line counter to our CSV, capitalize the car field and change the price to be in Ks (1000s).\n\n```js\nfunction addCounter() {\n  let counter = 1;\n  return (item) => ({\n    counter: counter++,\n    ...item,\n    car: item.car.toUpperCase(),\n    price: item.price / 1000,\n  });\n}\n```\n\nThen you can add `addCounter()` to the `transforms` array.\nThe reason to wrap the actual transform in a factory function is so the counter always starts with one and you can reuse it. But it's not strictly necessary.\n\n#### Built-in Transforms\n\nThere is a number of built-in transform provider by the library.\n\n```js\nconst {\n  transforms: { unwind, flatten },\n} = require('json2csv');\n```\n\n##### Unwind\n\nThe `unwind` transform deconstructs an array field from the input item to output a row for each element. It's similar to MongoDB's \\$unwind aggregation.\n\nThe transform needs to be instantiated and takes an options object as arguments containing:\n\n- `paths` - Array of Strings, list the paths to the fields to be unwound. It's mandatory and should not be empty.\n- `blankOut` - Boolean, unwind using blank values instead of repeating data. Defaults to `false`.\n\n```js\n// Default\nunwind({ paths: ['fieldToUnwind'] });\n\n// Blanking out repeated data\nunwind({ paths: ['fieldToUnwind'], blankOut: true });\n```\n\n##### Flatten\n\nFlatten nested JavaScript objects into a single level object.\n\nThe transform needs to be instantiated and takes an options object as arguments containing:\n\n- `objects` - Boolean, whether to flatten JSON objects or not. Defaults to `true`.\n- `arrays`- Boolean, whether to flatten Arrays or not. Defaults to `false`.\n- `separator` - String, separator to use between nested JSON keys when flattening a field. Defaults to `.`.\n\n```js\n// Default\nflatten();\n\n// Custom separator '__'\nflatten({ separator: '_' });\n\n// Flatten only arrays\nflatten({ objects: false, arrays: true });\n```\n\n### Formatters\n\njson2csv supports formatters. A formatter is a function that receives the raw js value of a given type and formats it as a valid CSV cell. Supported types are the types returned by `typeof` i.e. `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` and `object`.\n\nThere is a special type of formatter that only applies to the CSV headers if they are present. This is the `header` formatter and by default it uses the `string` formatter.\n\nPay special attention to the `string` formatter since other formatters like the `headers` or `object` formatters, rely on the `string` formatter for the stringification.\n\n#### Custom Formatters\n\n```js\nfunction formatType(itemOfType) {\n  // format object\n  return formattedItem;\n}\n```\n\nor using ES6\n\n```js\nconst formatType = (itemOfType) => {\n  // apply tranformations or create new object\n  return itemOfType;\n};\n```\n\nFor example, let's format functions as their name or 'unknown'.\n\n```js\nconst functionNameFormatter = (item) => item.name || 'unknown';\n```\n\nThen you can add `{ function: functionNameFormatter }` to the `formatters` object.\n\nA less trivial example would be to ensure that string cells never take more than 20 characters.\n\n```js\nconst stringFixedFormatter = (stringLength, ellipsis = '...') => (item) =>\n  item.length <= stringLength\n    ? item\n    : `${item.slice(0, stringLength - ellipsis.length)}${ellipsis}`;\n```\n\nThen you can add `{ string: stringFixedFormatter(20) }` to the `formatters` object.\nOr `stringFixedFormatter(20, '')` to not use the ellipsis and just clip the text.\nAs with the sample transform in the previous section, the reason to wrap the actual formatter in a factory function is so it can be parameterized easily.\n\nKeep in mind that the above example doesn't quote or escape the string which is problematic. A more realistic example could use our built-in string formatted to do the quoting and escaping like:\n\n```js\nconst { formatters: { string: defaultStringFormatter } } = require('json2csv');\n\nconst stringFixedFormatter = (stringLength, ellipsis = '...', stringFormatter = defaultStringFormatter()) => (item) => item.length <= stringLength ? item :  stringFormatter(`${item.slice(0, stringLength - ellipsis.length)}${ellipsis})`;\n```\n\n#### Built-in Formatters\n\nThere is a number of built-in formatters provider by the library.\n\n```js\nconst {\n  formatters: {\n    default: defaultFormatter,\n    number: numberFormatter,\n    string: stringFormatter,\n    stringQuoteOnlyIfNecessary: stringQuoteOnlyIfNecessaryFormatter,\n    stringExcel: stringExcelFormatter,\n    symbol: symbolFormatter,\n    object: objectFormatter,\n  },\n} = require('json2csv');\n```\n\n##### Default\n\nThis formatter just relies on standard JavaScript stringification.\nThis is the default formatter for `undefined`, `boolean`, `number` and `bigint` elements.\n\nIt's not a factory but the formatter itself.\n\n```js\n{\n  undefined: defaultFormatter,\n  boolean: defaultFormatter,\n  number: defaultFormatter,\n  bigint: defaultFormatter,\n}\n```\n\n##### Number\n\nFormat numbers with a fixed amount of decimals\n\nThe formatter needs to be instantiated and takes an options object as arguments containing:\n\n- `separator` - String, separator to use between integer and decimal digits. Defaults to `.`. It's crucial that the decimal separator is not the same character as the CSV delimiter or the result CSV will be incorrect.\n- `decimals` - Number, amount of decimals to keep. Defaults to all the available decimals.\n\n```js\n{\n  // 2 decimals\n  number: numberFormatter(),\n\n  // 3 decimals\n  number: numberFormatter(3)\n}\n```\n\n##### String\n\nFormat strings quoting them and escaping illegal characters if needed.\n\nThe formatter needs to be instantiated and takes an options object as arguments containing:\n\n- `quote` - String, quote around cell values and column names. Defaults to `\"`.\n- `escapedQuote` - String, the value to replace escaped quotes in strings. Defaults to double-quotes (for example `\"\"`).\n\nThis is the default for `string` elements.\n\n```js\n{\n  // Uses '\"' as quote and '\"\"' as escaped quote\n  string: stringFormatter(),\n\n  // Use single quotes `'` as quotes and `''` as escaped quote\n  string: stringFormatter({ quote: '\\'' }),\n\n  // Never use quotes\n  string: stringFormatter({ quote: '' }),\n\n  // Use '\\\"' as escaped quotes\n  string: stringFormatter({ escapedQuote: '\\\"' }),\n}\n```\n\n##### String Quote Only Necessary\n\nThe default string formatter quote all strings. This is consistent but it is not mandatory according to the CSV standard. This formatter only quote strings if they don't contain quotes (by default `\"`), the CSV separator character (by default `,`) or the end-of-line (by default `\\n` or `\\r\\n` depending on you operating system).\n\nThe formatter needs to be instantiated and takes an options object as arguments containing:\n\n- `quote` - String, quote around cell values and column names. Defaults to `\"`.\n- `escapedQuote` - String, the value to replace escaped quotes in strings. Defaults to 2x`quotes` (for example `\"\"`).\n- `eol` - String, overrides the default OS line ending (i.e. `\\n` on Unix and `\\r\\n` on Windows). Ensure that you use the same `eol` here as in the json2csv options.\n\n```js\n{\n  // Uses '\"' as quote, '\"\"' as escaped quote and your OS eol\n  string: stringQuoteOnlyIfNecessaryFormatter(),\n\n  // Use single quotes `'` as quotes, `''` as escaped quote and your OS eol\n  string: stringQuoteOnlyIfNecessaryFormatter({ quote: '\\'' }),\n\n  // Never use quotes\n  string: stringQuoteOnlyIfNecessaryFormatter({ quote: '' }),\n\n  // Use '\\\"' as escaped quotes\n  string: stringQuoteOnlyIfNecessaryFormatter({ escapedQuote: '\\\"' }),\n\n  // Use linux EOL regardless of your OS\n  string: stringQuoteOnlyIfNecessaryFormatter({ eol: '\\n' }),\n}\n```\n\n##### String Excel\n\nConverts string data into normalized Excel style data after formatting it using the given string formatter.\n\nThe formatter needs to be instantiated and takes no arguments.\n\n```js\n{\n  string: stringExcelFormatter,\n}\n```\n\n##### Symbol\n\nFormat the symbol as its string value and then use the given string formatter i.e. `Symbol('My Symbol')` is formatted as `\"My Symbol\"`.\n\nThe formatter needs to be instantiated and takes an options object as arguments containing:\n\n- `stringFormatter` - Boolean, whether to flatten JSON objects or not. Defaults to our built-in `stringFormatter`.\n\nThis is the default for `symbol` elements.\n\n```js\n{\n  // Uses the default string formatter\n  symbol: symbolFormatter(),\n\n  // Uses custom string formatter\n  // You rarely need to this since the symbol formatter will use the string formatter that you set.\n  symbol: symbolFormatter(myStringFormatter()),\n}\n```\n\n##### Object\n\nFormat the object using `JSON.stringify` and then the given string formatter.\nSome object types likes `Date` or Mongo's `ObjectId` are automatically quoted by `JSON.stringify`. This formatter, remove those quotes and uses the given string formatter for correct quoting and escaping.\n\nThe formatter needs to be instantiated and takes an options object as arguments containing:\n\n- `stringFormatter` - Boolean, whether to flatten JSON objects or not. Defaults to our built-in `stringFormatter`.\n\nThis is the default for `function` and `object` elements. `function`'s are formatted as empty ``.\n\n```js\n{\n  // Uses the default string formatter\n  object: objectFormatter(),\n\n  // Uses custom string formatter\n  // You rarely need to this since the object formatter will use the string formatter that you set.\n  object: objectFormatter(myStringFormatter()),\n}\n```\n\n### json2csv Parser (Synchronous API)\n\n`json2csv` can also be used programmatically as a synchronous converter using its `parse` method.\n\n```js\nconst { Parser } = require('json2csv');\n\nconst fields = ['field1', 'field2', 'field3'];\nconst opts = { fields };\n\ntry {\n  const parser = new Parser(opts);\n  const csv = parser.parse(myData);\n  console.log(csv);\n} catch (err) {\n  console.error(err);\n}\n```\n\nyou can also use the convenience method `parse`\n\n```js\nconst { parse } = require('json2csv');\n\nconst fields = ['field1', 'field2', 'field3'];\nconst opts = { fields };\n\ntry {\n  const csv = parse(myData, opts);\n  console.log(csv);\n} catch (err) {\n  console.error(err);\n}\n```\n\nBoth of the methods above load the entire JSON in memory and do the whole processing in-memory while blocking Javascript event loop. For that reason is rarely a good reason to use it until your data is very small or your application doesn't do anything else.\n\n### json2csv Async Parser (Streaming API)\n\nThe synchronous API has the downside of loading the entire JSON array in memory and blocking JavaScript's event loop while processing the data. This means that your server won't be able to process more request or your UI will become irresponsive while data is being processed. For those reasons, it is rarely a good reason to use it unless your data is very small or your application doesn't do anything else.\n\nThe async parser processes the data as a non-blocking stream. This approach ensures a consistent memory footprint and avoid blocking JavaScript's event loop. Thus, it's better suited for large datasets or system with high concurrency.\n\nOne very important difference between the asynchronous and the synchronous APIs is that using the asynchronous API json objects are processed one by one. In practice, this means that only the fields in the first object of the array are automatically detected and other fields are just ignored. To avoid this, it's advisable to ensure that all the objects contain exactly the same fields or provide the list of fields using the `fields` option.\n\nThe async API takes a second options arguments that is directly passed to the underlying streams and accepts the same options as the standard [Node.js streams](https://nodejs.org/api/stream.html#stream_new_stream_duplex_options).\n\nInstances of `AsyncParser` expose three objects expose a `parse` method similar to the sync API which takes both JSON arrays/objects and readable streams as input and returns a stream that produces the CSV.\n\n```js\nconst { AsyncParser } = require('json2csv');\n\nconst fields = ['field1', 'field2', 'field3'];\nconst opts = { fields };\nconst transformOpts = { highWaterMark: 8192 };\n\nconst asyncParser = new AsyncParser(opts, transformOpts);\n\nlet csv = '';\nasyncParser\n  .parse(data)\n  .on('data', (chunk) => (csv += chunk.toString()))\n  .on('end', () => console.log(csv))\n  .on('error', (err) => console.error(err))\n  // You can also listen for events on the conversion and see how the header or the lines are coming out.\n  .on('header', (header) => console.log(header))\n  .on('line', (line) => console.log(line));\n```\n\nUsing the async API you can transform streaming JSON into CSV and output directly to a writable stream.\n\n```js\nconst { createReadStream, createWriteStream } = require('fs');\nconst { AsyncParser } = require('json2csv');\n\nconst fields = ['field1', 'field2', 'field3'];\nconst opts = { fields };\nconst transformOpts = { highWaterMark: 8192 };\n\nconst input = createReadStream(inputPath, { encoding: 'utf8' });\nconst output = createWriteStream(outputPath, { encoding: 'utf8' });\n\nconst asyncParser = new AsyncParser(opts, transformOpts);\n\nasyncParser.parse(input).pipe(output);\n```\n\n`AsyncParser` also exposes a convenience `promise` method which turns the stream into a promise and resolves the whole CSV:\n\n```js\nconst { AsyncParser } = require('json2csv');\n\nconst fields = ['field1', 'field2', 'field3'];\nconst opts = { fields };\nconst transformOpts = { highWaterMark: 8192 };\n\nconst asyncParser = new AsyncParser(opts, transformOpts);\n\nlet csv = await asyncParser.parse(data).promise();\n```\n\n### json2csv Transform (Streaming API)\n\njson2csv also exposes the raw stream transform so you can pipe your json content into it. This is the same Transform that `AsyncParser` uses under the hood.\n\n```js\nconst { createReadStream, createWriteStream } = require('fs');\nconst { Transform } = require('json2csv');\n\nconst fields = ['field1', 'field2', 'field3'];\nconst opts = { fields };\nconst transformOpts = { highWaterMark: 16384, encoding: 'utf-8' };\n\nconst input = createReadStream(inputPath, { encoding: 'utf8' });\nconst output = createWriteStream(outputPath, { encoding: 'utf8' });\nconst json2csv = new Transform(opts, transformOpts);\n\nconst processor = input.pipe(json2csv).pipe(output);\n\n// You can also listen for events on the conversion and see how the header or the lines are coming out.\njson2csv\n  .on('header', (header) => console.log(header))\n  .on('line', (line) => console.log(line))\n  .on('error', (err) => console.log(err));\n```\n\nThe stream API can also work in object mode. This is useful when you have an input stream in object mode or if you are getting JSON objects one by one and want to convert them to CSV as they come.\n\n```js\nconst { Transform } = require('json2csv');\nconst { Readable } = require('stream');\n\nconst input = new Readable({ objectMode: true });\ninput._read = () => {};\n// myObjectEmitter is just a fake example representing anything that emit objects.\nmyObjectEmitter.on('object', (obj) => input.push(obj));\n// Pushing a null close the stream\nmyObjectEmitter.end(() => input.push(null));\n\nconst output = process.stdout;\n\nconst opts = {};\nconst transformOpts = { objectMode: true };\n\nconst json2csv = new Transform(opts, transformOpts);\nconst processor = input.pipe(json2csv).pipe(output);\n```\n\n## Upgrading\n\n### Upgrading from 5.X to 6.X\n\nThe CLI hasn't changed at all.\n\n#### Formatters\n\nIn the JavaScript modules, `formatters` are introduced and the `quote`, `escapedQuote` and `excelStrings` options are removed.\n\nCustom `quote` and `escapedQuote` are applied by setting the properties in the `string` formatter.\n\n```js\nconst { Parser } = require('json2csv');\nconst json2csvParser = new Parser({ quote: \"'\", escapedQuote: \"\\\\'\" });\nconst csv = json2csvParser.parse(myData);\n```\n\nshould be replaced by\n\n```js\nconst { Parser, formatter: { string: stringFormatter } } = require('json2csv');\nconst json2csvParser = new Parser({\n  formatters: {\n    string: stringFormatter({ quote: '\\'', escapedQuote: '\\\\\\'' })),\n  }\n});\nconst csv = json2csvParser.parse(myData);\n```\n\n`excelStrings` can be used by using the `stringExcel` formatter.\n\n```js\nconst { Parser } = require('json2csv');\nconst json2csvParser = new Parser({\n  quote: \"'\",\n  escapedQuote: \"\\\\'\",\n  excelStrings: true,\n});\nconst csv = json2csvParser.parse(myData);\n```\n\nshould be replaced by\n\n```js\nconst {\n  Parser,\n  formatter: { stringExcel: stringExcelFormatter },\n} = require('json2csv');\nconst json2csvParser = new Parser({\n  formatters: {\n    string: stringExcelFormatter,\n  },\n});\nconst csv = json2csvParser.parse(myData);\n```\n\n#### AsyncParser\n\nAsync parser have been simplified to be a class with a single `parse` method which replaces the previous `fromInput` method. `throughTransform` and `toOutput` can be replaced by Node's standard [pipe](https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options) method or the newer [pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback) utility.\n\nWhat used to be\n\n```js\nconst { AsyncParser } = require('json2csv');\nconst json2csvParser = new AsyncParser();\nconst csv = await json2csvParser\n  .fromInput(myData)\n  .throughTransform(myTransform)\n  .toOutput(myOutput);\n```\n\nshould be replaced by\n\n```js\nconst { AsyncParser } = require('json2csv');\nconst json2csvParser = new AsyncParser();\njson2csvParser.parse(myData.pipe(myTransform)).pipe(myOutput);\n```\n\nThe `promise` method has been kept but it doesn't take any argument as it used to. Now it always keeps the whole CSV and returns it.\n\nWhat used to be\n\n```js\nconst { AsyncParser } = require('json2csv');\nconst json2csvParser = new AsyncParser();\nconst csv = await json2csvParser.fromInput(myData).promise();\n```\n\nshould be replaced by\n\n```js\nconst { AsyncParser } = require('json2csv');\nconst json2csvParser = new AsyncParser();\nconst csv = await json2csvParser.parse(myData).promise();\n```\n\nIf you want to wait for the stream to finish but not keep the CSV in memory you can use the [stream.finished](https://nodejs.org/api/stream.html#stream_stream_finished_stream_options_callback) utility from Node's stream module.\n\nFinally, the `input`, `transform` and `processor` properties have been remove.\n`input` is just your data stream.\n`transform` and `processor` are equivalent to the return of the `parse` method.\n\nBefore you could instantiate an `AsyncParser` and push data into it. Now you can simply pass the data as the argument to the `parse` method if you have the entire dataset or you can manually create an array and push data to it.\n\nWhat used to be\n\n```js\nasyncParser.processor\n  .on('data', (chunk) => (csv += chunk.toString()))\n  .on('end', () => console.log(csv))\n  .on('error', (err) => console.error(err));\n\nmyData.forEach((item) => asyncParser.input.push(item));\nasyncParser.input.push(null); // Sending `null` to a stream signal that no more data is expected and ends it.\n```\n\nnow can be done as\n\n```js\nasyncParser\n  .parse(myData)\n  .on('data', (chunk) => (csv += chunk.toString()))\n  .on('end', () => console.log(csv))\n  .on('error', (err) => console.error(err));\n```\n\nor done manually as\n\n```js\nconst { Readable } = require('stream');\n\nconst myManualInput = new Readable({ objectMode: true });\nmyManualInput._read = () => {};\n\nasyncParser\n  .parse(myManualInput)\n  .on('data', (chunk) => (csv += chunk.toString()))\n  .on('end', () => console.log(csv))\n  .on('error', (err) => console.error(err));\n\nmyData.forEach((item) => myManualInput.push(item)); // This is useful when the data is coming asynchronously from a request or ws for example.\nmyManualInput.push(null);\n```\n\n### Upgrading from 4.X to 5.X\n\nIn the CLI, the config file option, `-c`, used to be a list of fields and now it's expected to be a full configuration object.\n\nThe `stringify` option hass been removed.\n\n`doubleQuote` has been renamed to `escapedQuote`.\n\nIn the javascript Javascript modules, `transforms` are introduced and all the `unwind` and `flatten` -related options has been moved to their own transforms.\n\nWhat used to be\n\n```js\nconst { Parser } = require('json2csv');\nconst json2csvParser = new Parser({\n  unwind: paths,\n  unwindBlank: true,\n  flatten: true,\n  flattenSeparator: '__',\n});\nconst csv = json2csvParser.parse(myData);\n```\n\nshould be replaced by\n\n```js\nconst {\n  Parser,\n  transform: { unwind, flatten },\n} = require('json2csv');\nconst json2csvParser = new Parser({\n  transforms: [unwind({ paths, blankOut: true }), flatten('__')],\n});\nconst csv = json2csvParser.parse(myData);\n```\n\nYou can se the documentation for json2csv v4.X.X [here](https://github.com/zemirco/json2csv/blob/v4/README.md).\n\n### Upgrading from 3.X to 4.X\n\nWhat in 3.X used to be\n\n```js\nconst json2csv = require('json2csv');\nconst csv = json2csv({ data: myData, fields: myFields, unwindPath: paths, ... });\n```\n\nshould be replaced by\n\n```js\nconst { Parser } = require('json2csv');\nconst json2csvParser = new Parser({ fields: myFields, unwind: paths, ... });\nconst csv = json2csvParser.parse(myData);\n```\n\nor the convenience method\n\n```js\nconst json2csv = require('json2csv');\nconst csv = json2csv.parse(myData, { fields: myFields, unwind: paths, ... });\n```\n\nPlease note that many of the configuration parameters have been slightly renamed. Please check one by one that all your parameters are correct.\nYou can se the documentation for json2csv 3.11.5 [here](https://github.com/zemirco/json2csv/blob/v3.11.5/README.md).\n\n## Known Gotchas\n\n### Excel support\n\n#### Avoiding excel auto-formatting\n\nExcel tries to automatically detect the format of every field (number, date, string, etc.) regardless of whether the field is quoted or not.\n\nThis might produce few undesired effects with, for example, serial numbers:\n\n- Large numbers are displayed using scientific notation\n- Leading zeros are stripped.\n\nEnabling the `excelString` option produces an Excel-specific CSV file that forces Excel to interpret string fields as strings. Please note that the CSV will look incorrect if viewing it somewhere else than Excel.\n\n#### Avoiding CSV injection\n\nAs part of Excel automatically format detection, fields regarded as formulas (starting with `=`, `+`, `-` or `@`) are interpreted regardless of whether the field is quoted or not, creating a security risk (see [CSV Injection](https://www.owasp.org/index.php/CSV_Injection).\n\nThis issue has nothing to do with the CSV format, since CSV knows nothing about formulas, but with how Excel parses CSV files.\n\nEnabling the `excelString` option produces an Excel-specific CSV file that forces Excel to interpret string fields as strings. Please note that the CSV will look incorrect if viewing it somewhere else than Excel.\n\n#### Preserving new lines\n\nExcel only recognizes `\\r\\n` as valid new line inside a cell.\n\n#### Unicode Support\n\nExcel can display Unicode correctly (just setting the `withBOM` option to true). However, Excel can't save unicode so, if you perform any changes to the CSV and save it from Excel, the Unicode characters will not be displayed correctly.\n\n### PowerShell escaping\n\nPowerShell do some estrange double quote escaping escaping which results on each line of the CSV missing the first and last quote if outputting the result directly to stdout. Instead of that, it's advisable that you write the result directly to a file.\n\n## Development\n\n### Pulling the repo\n\nAfter you clone the repository you just need to install the required packages for development by runnning following command under json2csv dir.\n\n```sh\n$ npm install\n```\n\n### Building\n\njson2csv is packaged using `rollup`. You can generate the packages running:\n\n```sh\nnpm run build\n```\n\nwhich generates 3 files under the `dist folder`:\n\n- `json2csv.umd.js` UMD module transpiled to ES5\n- `json2csv.esm.js` ES5 module (import/export)\n- `json2csv.cjs.js` CommonJS module\n\nWhen you use packaging tools like webpack and such, they know which version to use depending on your configuration.\n\n### Linting & Testing\n\nRun the following command to check the code style.\n\n```sh\n$ npm run lint\n```\n\nRun the following command to run the tests and return coverage\n\n```sh\n$ npm run test-with-coverage\n```\n\n### Contributing changes\n\nBefore making any pull request please ensure sure that your code is formatted, test are passing and test coverage haven't decreased.\n\n## License\n\nSee [LICENSE.md].\n\n[npm-badge]: https://badge.fury.io/js/json2csv.svg\n[npm-badge-url]: http://badge.fury.io/js/json2csv\n[travis-badge]: https://travis-ci.org/zemirco/json2csv.svg\n[travis-badge-url]: https://travis-ci.org/zemirco/json2csv\n[coveralls-badge]: https://coveralls.io/repos/zemirco/json2csv/badge.svg?branch=master\n[coveralls-badge-url]: https://coveralls.io/r/zemirco/json2csv?branch=master\n[changelog]: https://github.com/zemirco/json2csv/blob/master/CHANGELOG.md\n[license.md]: https://github.com/zemirco/json2csv/blob/master/LICENSE.md\n","readmeFilename":"README.md","gitHead":"fe4079779deb72f7342c3dc77058190f7727d084","bugs":{"url":"https://github.com/zemirco/json2csv/issues"},"_id":"json2csv@6.0.0-alpha.0","_nodeVersion":"12.20.0","_npmVersion":"6.14.8","dist":{"integrity":"sha512-Sc7Maca9abvW0eiiwTR/TsR45I9CAAtXNSu2hUa6WnuHDB6gG0hwHVYXeIyVO+0CBoBFy70Mm3afFE+OyJIrIA==","shasum":"a8133daedc8ad8c95e3b2b626766d68be8be2da1","tarball":"http://registry-npm.ywwl.com/json2csv/download/json2csv-6.0.0-alpha.0.tgz","fileCount":30,"unpackedSize":398901,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgdyoACRA9TVsSAnZWagAACZ4P+wWHDnmBp+l0aT/Sdg6m\nQNd8ykWk6HfwT1/lFtQE3iv+fBjtwgcknH+Ip7QeR/s1r7rVhHDUQf2fq7un\nXjZrMoFUS0TOyg74s+Pvaqlz//8sPVdcyTBDInvNvRHx6VrySOpon4TsASdl\ndL5crPo9S7wcHH3ODmcyo8Yy0+sdv0H4BukOlqSTzZIcAFrkSwaCmW2yjgY4\nLmYlO1s4LBzI3/lDZ9pzOdT5QG47sHpn7kJO4gEtliaslvoC1CsxG1Ijdjbt\nxwT86fH1+cYNhOKKnXbHb3RLciag1Uig6ARtvEFvMtHnmGq8XGKu8p1/PK+t\nU/AHU0qVt+wW2XsgHJYdnAe0Jh8qrkAW0d4KRyRpTSS6WbbFYraeWHCyK0eJ\nuDpovbH3mYMb36LSuRUeiVrx1/dvrEijX6Dz10WmKJBo57DxO3OnfhNjupkJ\nD0Q9DLnU2cdmWjCJmpV9uqPHhNQmD76EJyecqGKTytov/J/5vRcnrsXZJOeL\n7qpNdFeqW7AqVB9ioOpG89q9zzYDrU+lKRHlemc0j4TLgv4ajkI97gdqlxTP\ngIT+bkDsalunZBs23iDhJQoINSjsudxxT8+bp2dfYT/al1plAIQ8HAK3JgOH\nwrLzlvIvegE0yC8hh+SbeKWMeXk/RVLrcEdIbBBKqt4vlVevlXQnb7j9DXi5\nbl3b\r\n=T6jZ\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHQxx32SAFFFW/2YKTxviJK2ITmxLfF72AHZFjKjCuytAiAj++P16TYtzLqDQo0jqYmcybjynKlElAsar3Ckq0umvg=="}],"size":97852,"noattachment":false,"key":"/json2csv/-/json2csv-6.0.0-alpha.0.tgz"},"_npmUser":{"name":"knownasilya","email":"knownasilya@gmail.com"},"directories":{},"maintainers":[{"name":"zemirco","email":"mirco.zeiss@gmail.com"},{"name":"knownasilya","email":"knownasilya@gmail.com"},{"name":"juanjodiaz","email":"juanjo.diazmo@gmail.com"},{"name":"azhang","email":"azhang@bottlenose.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/json2csv_6.0.0-alpha.0_1618422272224_0.7721492642369043"},"_hasShrinkwrap":false,"deprecated":"Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.","publish_time":1618422272419,"_cnpm_publish_time":1618422272419,"dist-tags":{"alpha":"6.0.0-alpha.0","latest":"6.0.0-alpha.2","prerelease":"4.0.0-alpha.2"}}