### Install json2csv CLI using NPM Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/cli.md Installs the json2csv CLI as a global dependency using NPM, making it accessible from any directory. ```bash npm install -g @json2csv/cli ``` -------------------------------- ### Install json2csv CLI using Yarn Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/cli.md Installs the json2csv CLI as a global dependency using Yarn, enabling its use from any location. ```bash yarn global add @json2csv/cli ``` -------------------------------- ### json2csv CLI Installation Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/quick-start.md Provides the command to globally install the json2csv CLI tool, enabling its use directly from the terminal for converting JSON files to CSV. ```bash $ npm install -g @json2csv/cli ``` -------------------------------- ### Install json2csv parser with NPM Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/parser.md Installs the json2csv parser as a dependency using NPM. This is a standard method for managing project dependencies in Node.js environments. ```bash npm install --save @json2csv/plainjs ``` -------------------------------- ### Install json2csv parser with Yarn Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/parser.md Installs the json2csv parser as a dependency using Yarn. Yarn is an alternative package manager for Node.js, offering similar functionality to NPM. ```bash yarn add --save @json2csv/plainjs ``` -------------------------------- ### Install json2csv NodeAsyncParser with NPM Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/node-async-parser.md Installs the json2csv NodeAsyncParser package using NPM. This is a prerequisite for using the asynchronous CSV parsing functionality in a Node.js environment. ```bash npm install --save @json2csv/node ``` -------------------------------- ### Install json2csv WHATWGTransformStream via NPM Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/whatwg-transform-stream.md Install the WHATWGTransformStream package for json2csv using NPM. This is the recommended method for Node.js environments and front-end projects using a module bundler. ```bash npm install --save @json2csv/whatwg ``` -------------------------------- ### Install json2csv Transforms via NPM Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/transforms.md Installs the json2csv transforms package as a dependency using NPM. This is the primary method for Node.js projects. ```bash $ npm install --save @json2csv/transforms ``` -------------------------------- ### json2csv CLI: JSON configuration for fields Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/cli.md An example of a JSON configuration file used with the json2csv CLI to define the fields to be included in the CSV output. ```json { "fields": ["carModel", "price", "color"] } ``` -------------------------------- ### Install json2csv NodeAsyncParser with Yarn Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/node-async-parser.md Installs the json2csv NodeAsyncParser package using Yarn. This command adds the asynchronous CSV parsing capabilities as a project dependency. ```bash yarn add --save @json2csv/node ``` -------------------------------- ### Install json2csv WHATWGTransformStream via Yarn Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/whatwg-transform-stream.md Install the WHATWGTransformStream package for json2csv using Yarn. This is an alternative package manager for Node.js environments and front-end projects. ```bash yarn add --save @json2csv/whatwg ``` -------------------------------- ### Install json2csv Transforms via Yarn Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/transforms.md Installs the json2csv transforms package as a dependency using Yarn. This is an alternative to NPM for managing project dependencies. ```bash $ yarn add --save @json2csv/transforms ``` -------------------------------- ### CLI: Configuration File for json2csv Source: https://context7.com/juanjodiaz/json2csv/llms.txt Presents an example JSON configuration file (`config.json`) used with the `json2csv` CLI tool to define complex conversion options such as field mappings with labels, delimiters, end-of-line characters, header inclusion, BOM, and transformations. ```json { "fields": [ { "label": "Full Name", "value": "name" }, { "label": "Email Address", "value": "email" }, { "label": "Registration Date", "value": "createdAt" } ], "delimiter": ",", "eol": "\n", "header": true, "includeEmptyRows": false, "withBOM": true, "transforms": [] } ``` -------------------------------- ### Live JSON to CSV Parsing Example (JavaScript) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/index.html This JavaScript code configures the docsify environment for a live parser. It defines the initial state for the parser's options, handles user input for JSON and CSV options, computes configuration objects for the parser, and provides methods to format JSON, parse JSON to CSV, and display errors. ```javascript window.$docsify = { name: 'json2csv', repo: 'juanjoDiaz/json2csv', loadSidebar: true, auto2top: true, maxLevel: 4, subMaxLevel: 2, vueMounts: { '#live-parser': { data() { return { showOptions: false, showOptionsForm: true, inputOptions: { ndjson: undefined, fields: undefined, }, formattersOptions: {}, transformsOptions: { unwind: {}, flatten: {}, }, csvOptions: { defaultValue: undefined, delimiter: undefined, eol: undefined, header: undefined, includeEmptyRows: undefined, withBOM: undefined, }, inputJSON: '', outputCSV: '', }; }, computed: { includeHeader: { get() { return this.csvOptions.header || true; }, set(value) { this.csvOptions.header = value; } }, unwindConfig() { if (!this.transformsOptions.unwind.paths) return; return { paths: this.transformsOptions.unwind.paths.split(','), blankOut: this.transformsOptions.unwind.blankOut, }; }, flattenConfig() { if (!this.transformsOptions.flatten.objects && !this.transformsOptions.flatten.arrays) return; return { objects: this.transformsOptions.flatten.objects, arrays: this.transformsOptions.flatten.arrays, separator: this.transformsOptions.flatten.separator, }; }, configJSON() { const transforms = []; if (this.unwindConfig) { transforms.push(new Json2csvTransforms.unwind(this.unwindConfig)); } if (this.flattenConfig) { transforms.push(new Json2csvTransforms.flatten(this.flattenConfig)); } return { ...this.inputOptions, transforms: transforms.length > 0 ? transforms : undefined, fields: this.inputOptions.fields && this.inputOptions.fields.split(','), ...this.csvOptions, }; }, configText() { let config = JSON.stringify({ ...this.inputOptions, transforms: this.unwindConfig || this.flattenConfig ? 'placeholder' : undefined, fields: this.inputOptions.fields && this.inputOptions.fields.split(','), ...this.csvOptions, }, null, 4); config = config.replace(/"(\s\*)transforms": "placeholder"/m, `"transforms": [ ${[ this.unwindConfig ? `unwind(${JSON.stringify(this.unwindConfig, null, 4).replace(/\n/g, '\n ')})` : '', this.flattenConfig ? `flatten(${JSON.stringify(this.flattenConfig, null, 4).replace(/\n/g, '\n ')})` : '' ].filter(t => t).join(',\n ')} ]`); return config; } }, methods: { formatJSON() { try { this.inputJSON = JSON.stringify(JSON.parse(this.inputJSON), null, 4); } catch (err) { this.showError('Error formatting your JSON', err); } }, parseJSON() { const parser = new Json2csvStreamParser(this.configJSON); this.outputCSV = ''; parser.onData = data => { this.outputCSV += data; }; parser.onError = err => this.showError('Error parsing your JSON', err.message); parser.write(this.inputJSON); parser.end(); }, showError(title, message) { const notification = document.createElement('div'); notification.classList.add('notification', 'is-danger', 'alert'); const titleEl = document.createElement('h1'); titleEl.innerText = title; notification.appendChild(titleEl); const messageEl = document.createElement('div'); messageEl.innerText = message; notification.appendChild(messageEl); notification.addEventListener('click', () => document.body.removeChild(notification)); document.body.appendChild(notification); setTimeout(() => notification.dispatchEvent(new Event('click')), 2000); } } } }, tabs: { sync: true } } ``` -------------------------------- ### Implement Excel String Formatting in json2csv (JavaScript) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/migration-guides/5-to-6.md This example demonstrates replacing the 'excelStrings: true' option with the 'stringExcel' formatter in json2csv. This formatter handles Excel-specific string formatting requirements. It requires the '@json2csv/plainjs' and '@json2csv/formatters' packages. ```javascript const { stringExcel: stringExcelFormatter } = require('@json2csv/formatters'); const { Parser } = require('@json2csv/plainjs'); const json2csvParser = new Parser({ formatters: { string: stringExcelFormatter, } }); const csv = json2csvParser.parse(myData); ``` -------------------------------- ### Synchronous JSON to CSV Conversion (PlainJS Parser) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/quick-start.md This snippet demonstrates how to use the synchronous PlainJS Parser from '@json2csv/plainjs' to convert JSON data to CSV. It loads the entire JSON in memory, which is suitable for small datasets but can block the event loop. Installation requires 'npm install --save @json2csv/plainjs'. ```javascript import { Parser } from '@json2csv/plainjs'; try { const parser = new Parser(); const csv = parser.parse(myData); console.log(csv); } catch (err) { console.error(err); } ``` -------------------------------- ### Reimplementing Convenience Methods parse and parseAsync Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/migration-guides/5-to-6.md Shows how to recreate the removed `parse` and `parseAsync` convenience methods using the new module structure in json2csv v6.X. These methods simplify the parsing process by encapsulating parser instantiation. ```javascript const { Parser } = require('@json2csv/plainjs'); const parse = (data, opts) => new Parser(opts).parse(data); ``` ```javascript const { AsyncParser } = require('@json2csv/node'); const parseAsync = (data, opts, transformOpts) => new AsyncParser(opts, transformOpts).parse(data).promise(); ``` -------------------------------- ### json2csv: Input file, data selection, output to stdout Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/cli/README.md Example demonstrating how to use json2csv to read from an input JSON file, select specific fields, and output the resulting CSV data directly to the standard output. ```bash $ json2csv -i input.json -f carModel,price,color carModel,price,color "Audi",10000,"blue" "BMW",15000,"red" "Mercedes",20000,"yellow" "Porsche",30000,"green" ``` -------------------------------- ### Install json2csv Formatters using NPM Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/formatters.md Installs the json2csv formatters package as a dependency using NPM. This command adds the package to your project's node_modules directory and updates your package.json file. ```bash npm install --save @json2csv/formatters ``` -------------------------------- ### json2csv: Using config file for fields, output to file Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/cli/README.md This example illustrates how to specify the fields for CSV conversion using an external JSON configuration file with json2csv, and then outputting the result to a specified file. ```bash $ json2csv -i input.json -c config.json -o out.csv where the file `config.json` contains { "fields": ["carModel", "price", "color"] } ``` -------------------------------- ### Install json2csv Formatters using Yarn Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/formatters.md Installs the json2csv formatters package as a dependency using Yarn. This command adds the package to your project's node_modules directory and updates your package.json file. ```bash yarn add --save @json2csv/formatters ``` -------------------------------- ### json2csv CLI: Input from stdin Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/cli.md Converts JSON data piped to stdin into CSV format. This example demonstrates selecting the 'price' field and assumes the input is provided interactively or via a pipe. ```bash $ json2csv -f price [{"price":1000},{"price":2000}] ``` -------------------------------- ### json2csv: Input file, data selection, pretty output to stdout Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/cli/README.md This example shows how to use json2csv to generate a CSV output in a human-readable, pretty-printed table format directly to the console, after selecting specific fields from an input JSON file. ```bash $ json2csv -i input.json -f carModel,price,color -p ┌────────────────────┬───────────────┬───────────────┐ │ "carModel" │ "price" │ "color" │ ├────────────────────┼───────────────┼───────────────┤ │ "Audi" │ 10000 │ "blue" │ ├────────────────────┼───────────────┼───────────────┤ │ "BMW" │ 15000 │ "red" │ ├────────────────────┼───────────────┼───────────────┤ │ "Mercedes" │ 20000 │ "yellow" │ ├────────────────────┼───────────────┼───────────────┤ │ "Porsche" │ 30000 │ "green" │ └────────────────────┴───────────────┴───────────────┘ ``` -------------------------------- ### json2csv: Input file, data selection, output to file Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/cli/README.md Demonstrates saving the CSV output to a specified file after selecting fields from an input JSON file using json2csv. The example also shows how to verify the content of the output file. ```bash $ json2csv -i input.json -f carModel,price,color -o out.csv $ cat out.csv carModel,price,color "Audi",10000,"blue" "BMW",15000,"red" "Mercedes",20000,"yellow" "Porsche",30000,"green" ``` -------------------------------- ### Manual AsyncParser Input Handling with Readable Stream Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/migration-guides/5-to-6.md Shows how to manually handle input for `AsyncParser` by creating a `Readable` stream and pushing data, which is useful when data arrives asynchronously. This replaces the older `input.push()` method in json2csv v6.X. ```javascript import { Readable } from 'stream'; const myManualInput = new Readable({ objectMode: true }); myManualInput._read = () => {}; asyncParser.parse(myManualInput) .on('data', (chunk) => (csv += chunk.toString())) .on('end', () => console.log(csv)) .on('error', (err) => console.error(err)); myData.forEach(item => myManualInput.push(item)); // This is useful when the data is coming asynchronously from a request or ws for example. myManualInput.push(null); ``` -------------------------------- ### AsyncParser Direct Parsing with Data Input Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/migration-guides/5-to-6.md Demonstrates the simplified way to parse data directly using the `parse` method of `AsyncParser` in json2csv v6.X. This approach is suitable when the entire dataset is available at once, replacing the older `input.push()` pattern. ```javascript asyncParser.parse(myData) .on('data', (chunk) => (csv += chunk.toString())) .on('end', () => console.log(csv)) .on('error', (err) => console.error(err)); ``` -------------------------------- ### Stream-based JSON to CSV Conversion (Stream Parser) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/quick-start.md This snippet shows how to use the StreamParser from '@json2csv/plainjs' for efficient, stream-based JSON to CSV conversion. It processes data incrementally, preventing memory overload and event loop blocking, making it ideal for large datasets. Installation requires 'npm install --save @json2csv/plainjs'. It supports callbacks for data, end, errors, headers, and lines. ```javascript import { StreamParser } from '@json2csv/plainjs'; const parser = new StreamParser(); let csv = ''; parser.onData = (chunk) => (csv += chunk.toString()); parser.onEnd = () => console.log(csv); parser.onError = (err) => console.error(err); // You can also listen for events on the conversion and see how the header or the lines are coming out. parser.onHeader = (header) => console.log(header); parser.onLine = (line) => console.log(line); ``` -------------------------------- ### AsyncParser Stream Piping with Node.js pipe/pipeline Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/migration-guides/5-to-6.md Illustrates how to replace the `throughTransform` and `toOutput` methods of the `AsyncParser` with Node.js's standard `pipe` or `pipeline` utilities for stream manipulation in json2csv v6.X. ```javascript import { AsyncParser } from '@json2csv/node'); const json2csvParser = new AsyncParser(); json2csvParser.parse(myData.pipe(myTransform)).pipe(myOutput); ``` -------------------------------- ### Use Built-in Transforms via CLI with json2csv Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/transforms/README.md Shows how to apply built-in json2csv transforms directly from the command line interface. This example utilizes flags for unwinding, flattening, and specifying flatten separators. ```bash $ json2csv -i input.json \ --unwind "fieldToUnwind","fieldToUnwind.subfieldToUnwind" \ --unwind-blank \ --flatten-objects \ --flatten-arrays \ --flatten-separator "_" ``` -------------------------------- ### Unwind Transform Example with Node Transform Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/transforms.md Illustrates using the 'unwind' transform within a Node.js stream pipeline. This example involves reading from a file, transforming the data, and writing to another file. ```javascript import { createReadStream, createWriteStream } from 'fs'; import { Transform } from '@json2csv/node'; import { unwind } from '@json2csv/transforms'; const data = [ { "carModel": "Audi", "price": 0, "colors": ["blue","green","yellow"] }, { "carModel": "BMW", "price": 15000, "colors": ["red","blue"] }, { "carModel": "Mercedes", "price": 20000, "colors": "yellow" }, { "carModel": "Porsche", "price": 30000, "colors": ["green","teal","aqua"] }, { "carModel": "Tesla", "price": 50000, "colors": []} ]; const input = createReadStream(inputPath, { encoding: 'utf8' }); const output = createWriteStream(outputPath, { encoding: 'utf8' }); const opts = { transforms: [ unwind({ paths: ['colors'] }) ] }; const parser = new Transform(ops); const processor = input.pipe(parser).pipe(output); ``` -------------------------------- ### Node.js Transform Stream for JSON to CSV Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/quick-start.md This snippet demonstrates wrapping the Stream Parser in a Node.js Transform Stream for efficient JSON to CSV conversion within Node.js environments. It maintains a consistent memory footprint and avoids blocking the event loop. Installation requires 'npm install --save @json2csv/node'. It accepts stream options and supports similar events to the Stream Parser. ```javascript import { Transform } from 'stream'; import { StreamParser } from '@json2csv/node'; // Example usage within a Node.js stream pipeline would go here. // This snippet focuses on the concept and installation. // Actual implementation would involve creating and piping the stream. // Placeholder for stream creation if needed: // const jsonToCsvTransform = new StreamParser(); ``` -------------------------------- ### Unwind Transform Example with Stream Parser Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/transforms.md Shows how to use the 'unwind' transform with the 'StreamParser' class for processing data streams. This is useful for large datasets that don't fit into memory. ```javascript import { StreamParser } from '@json2csv/plainjs'; import { unwind } from '@json2csv/transforms'; const data = [ { "carModel": "Audi", "price": 0, "colors": ["blue","green","yellow"] }, { "carModel": "BMW", "price": 15000, "colors": ["red","blue"] }, { "carModel": "Mercedes", "price": 20000, "colors": "yellow" }, { "carModel": "Porsche", "price": 30000, "colors": ["green","teal","aqua"] }, { "carModel": "Tesla", "price": 50000, "colors": []} ]; const opts = { transforms: [ unwind({ paths: ['colors'] }) ] }; const parser = new StreamParser(opts, { objectMode: true }); let csv = ''; parser.onData = (chunk) => (csv += chunk.toString())); parser.onEnd = () => console.log(csv)); parser.onError = (err) => console.error(err)); data.forEach(record => parser.write(record)); ``` -------------------------------- ### JSON to CSV Conversion using CLI Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/formatters/README.md Provides examples of using the json2csv command-line interface to convert JSON files to CSV. It illustrates options for specifying input files, quote characters, and escaped quotes, as well as an alternative for using 'Excel strings'. ```bash $ json2csv -i input.json --quote '"' --escaped-quote '"' ``` ```bash $ json2csv -i input.json --excel-strings ``` -------------------------------- ### Importing json2csv Modules (Before and After) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/migration-guides/5-to-6.md Demonstrates how to update import statements when json2csv is split into several independent packages in version 6.X. This change separates pure JavaScript code from Node.js core library dependencies. ```javascript const { Parser, StreamParser, NodeTransform, NodeAsyncParser, WhatwgTransformStream, WhatwgAsyncParser, transforms: { flatten, unwind }, formatters: { number: numberFormatter, string: stringFormatter, stringExcel: stringExcelFormatter, stringQuoteOnlyIfNecessary: stringQuoteOnlyIfNecessaryFormatter }, } = require('json2csv'); ``` ```javascript const { Parser, StreamParser } = require('@json2csv/plainjs'); const { Transform, AsyncParser } = require('@json2csv/node'); const { TransformStream, AsyncParser } = require('@json2csv/whatwg'); const { flatten, unwind } = require('@json2csv/transforms'); const { number: numberFormatter, string: stringFormatter, stringExcel: stringExcelFormatter, stringQuoteOnlyIfNecessary: stringQuoteOnlyIfNecessaryFormatter } = require('@json2csv/formatters'); ``` -------------------------------- ### Unwind Transform Example with Node Async Parser Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/transforms.md Demonstrates the 'unwind' transform using the 'AsyncParser' in Node.js for asynchronous CSV processing. This is suitable for modern JavaScript environments and promise-based workflows. ```javascript import { AsyncParser } from '@json2csv/node'; import { unwind } from '@json2csv/transforms'; import { addCounter } from './custom-transforms'; const opts = { transforms: [ unwind({ paths: ['colors'] }) ] }; const parser = new AsyncParser(opts); let csv = await parser.parse(data).promise(); ``` -------------------------------- ### JavaScript: Excel-Compatible String Formatting Source: https://context7.com/juanjodiaz/json2csv/llms.txt Shows how to use the `stringExcel` formatter from @json2csv/formatters in JavaScript to ensure strings that might be interpreted as formulas by Excel (e.g., starting with '=', '+', '-') are properly escaped. ```javascript import { Parser } from '@json2csv/plainjs'; import { stringExcel } from '@json2csv/formatters'; const data = [ { id: '001', code: '=A1+B1', note: 'Leading zero preserved' }, { id: '002', code: '+1234', note: 'Plus sign preserved' } ]; const opts = { formatters: { string: stringExcel } }; const parser = new Parser(opts); const csv = parser.parse(data); console.log(csv); ``` -------------------------------- ### Custom Function Name Formatter Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/formatters/README.md An example of a custom formatter that formats functions by returning their 'name' property or 'unknown' if the name is not available. This is useful for representing functions in a CSV. ```javascript const functionNameFormatter = (item) => item.name || 'unknown'; ``` -------------------------------- ### CLI for JSON to CSV Conversion with Unwind Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/transforms.md This shows the command-line interface usage for converting JSON to CSV, specifically demonstrating the `--unwind` option. It's a simple bash command executed in the terminal, requiring the json2csv tool to be installed. ```bash $ json2csv -i data.json --unwind "color" ``` -------------------------------- ### Node Async Parser Usage for json2csv Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/quick-start.md Shows how to use the Node.js Async Parser from json2csv, which simplifies stream-based parsing by providing a single `parse` method and a `promise` method to get the entire CSV output as a promise. ```javascript import { AsyncParser } from '@json2csv/node'; const parser = new AsyncParser(); const csv = await parser.parse(data).promise(); ``` -------------------------------- ### json2csv v5 Transforms API: Unwind and Flatten in JavaScript Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/migration-guides/4-to-5.md Demonstrates the new approach to handling nested data structures in json2csv v5 using the 'transforms' API. It replaces the older 'unwind' and 'flatten' options with dedicated transform functions. This example shows how to import and use 'unwind' and 'flatten' transforms. ```javascript const { Parser, transform: { unwind, flatten }, } = require('json2csv'); const myData = [ { "field1": "value1", "nested": { "subfield": "subvalue" } }, { "field1": "value2", "nested": { "subfield": "another" } }, ]; const json2csvParser = new Parser({ transforms: [unwind({ paths: ['nested.subfield'], blankOut: true }), flatten('__')], }); const csv = json2csvParser.parse(myData); console.log(csv); ``` -------------------------------- ### AsyncParser .promise() Usage in json2csv v6.X Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/migration-guides/5-to-6.md Demonstrates the updated usage of the `.promise()` method on `AsyncParser` in json2csv v6.X. The method now always keeps the entire CSV in memory and returns it, simplifying asynchronous CSV generation. ```javascript import { AsyncParser } from '@json2csv/node'); const json2csvParser = new AsyncParser(); const csv = await json2csvParser.parse(myData).promise(); ``` -------------------------------- ### Realistic Parameterized String Formatter (JavaScript) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/formatters.md A more robust example of a parameterized custom string formatter that combines length limiting with proper CSV quoting and escaping using the default string formatter. It requires importing the default string formatter. ```javascript import { string as defaultStringFormatter } from '@json2csv/formatters'; const fixedLengthStringFormatter = (stringLength, ellipsis = '...', stringFormatter = defaultStringFormatter()) => (item) => item.length <= stringLength ? item : stringFormatter(`${item.slice(0, stringLength - ellipsis.length)}${ellipsis}`); ``` -------------------------------- ### CLI: Using Configuration File for Conversion Source: https://context7.com/juanjodiaz/json2csv/llms.txt Shows the command-line syntax for utilizing a JSON configuration file with the `json2csv` tool to perform a CSV conversion, applying all the settings defined within the specified configuration file. ```bash # Use the config file json2csv -i users.json -c config.json -o output.csv ``` -------------------------------- ### Stream Parsing JSON to CSV with Transforms (Plain JS) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/transforms.md This JavaScript example uses the `StreamParser` from '@json2csv/plainjs' to process JSON data in chunks. It configures the parser with unwind, flatten, and a custom addCounter transform, and demonstrates handling data, end, and error events. ```javascript import { StreamParser } from '@json2csv/plainjs'; import { unwind, flatten } from '@json2csv/transforms'; import { addCounter } from './custom-transforms'; const opts = { transforms: [ unwind({ paths: ['fieldToUnwind','fieldToUnwind.subfieldToUnwind'], blankOut: true }), flatten({ objects: true, arrays: true, separator: '_'}), addCounter() ] }; const parser = new StreamParser(opts); let csv = ''; parser.onData = (chunk) => (csv += chunk.toString()); parser.onEnd = () => console.log(csv); parser.onError = (err) => console.error(err); // You can also listen for events on the conversion and see how the header or the lines are coming out. parser.onHeader = (header) => console.log(header); parser.onLine = (line) => console.log(line); ``` -------------------------------- ### json2csv CLI: Initial CSV creation with headings Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/cli.md Creates an initial CSV file with specified headers and data from a JSON file. This command is typically the first step when building a CSV file incrementally. ```bash $ json2csv -i test.json -f name,version > test.csv ``` -------------------------------- ### StreamParser Initialization and Usage Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/stream-parser.md Demonstrates how to initialize the StreamParser and handle data, end, and error events. It also shows how to listen for header and line events for more granular processing. ```APIDOC ## StreamParser API ### Description Processes JSON data as it comes in, avoiding the need to load the entire dataset into memory. This prevents blocking the event loop, making it suitable for large datasets or systems with high concurrency. ### Method `new StreamParser(opts, asyncOpts)` ### Parameters #### Options (`opts`) * `ndjson` (Boolean) - Indicates that the data is in NDJSON format. Only effective when using the streaming API and not in object mode. * `fields` (DataSelector[]) - Defaults to toplevel JSON attributes. * `transforms` (Transform[]) - Array of transforms to apply to the data. * `formatters` (Formatters) - Object where keys are Javascript data types and values are formatters for those types. * `defaultValue` (Any) - Value to use when data is missing. Defaults to ``. * `delimiter` (String) - Delimiter of columns. Defaults to `,`. * `eol` (String) - Overrides the default OS line ending (e.g., `\n` on Unix and `\r\n` on Windows). * `header` (Boolean) - Determines whether the CSV file will contain a title column. Defaults to `true`. * `includeEmptyRows` (Boolean) - Includes empty rows. Defaults to `false`. * `withBOM` (Boolean) - Includes a BOM character. Defaults to `false`. #### Async Options (`asyncOpts`) Options used by the underlying parsing library to process the binary or text stream. Not relevant when running in `objectMode`. Buffering is only relevant if you expect very large strings/numbers in your JSON. * `stringBufferSize` (number) - Size of the buffer used to parse strings. Defaults to 0 (no buffering). Min valid value is 4. * `numberBufferSize` (number) - Size of the buffer used to parse numbers. Defaults to 0 (no buffering). ### Request Example ```js import { StreamParser } from '@json2csv/plainjs'; const opts = {}; const asyncOpts = {}; const parser = new StreamParser(opts, asyncOpts); let csv = ''; parser.onData = (chunk) => (csv += chunk.toString()); parser.onEnd = () => console.log(csv); parser.onError = (err) => console.error(err); // Optional: Listen for header and line events parser.onHeader = (header) => console.log('Header:', header); parser.onLine = (line) => console.log('Line:', line); // Assume 'readableStream' is a readable stream of JSON data // readableStream.pipe(parser); ``` ### Response This API processes data in chunks and does not return a single response. Instead, it emits events. #### Event: `data` - **chunk** (Buffer) - A chunk of the processed CSV data. #### Event: `end` - No parameters. Emitted when the entire stream has been processed. #### Event: `error` - **err** (Error) - An error object if any processing error occurs. #### Event: `header` (Optional) - **header** (String) - The generated CSV header row. #### Event: `line` (Optional) - **line** (String) - A processed CSV data row. ``` -------------------------------- ### Initialize json2csv StreamParser and Transforms (JavaScript) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/index.html This snippet demonstrates how to import and initialize the `Json2csvStreamParser` and its associated transforms (`flatten`, `unwind`) from the json2csv library using CDN links. It makes these components globally accessible. ```javascript import Json2csvStreamParser from "//cdn.jsdelivr.net/gh/juanjoDiaz/json2csv@7.0.7/dist/cdn/plainjs/StreamParser.js"; window.Json2csvStreamParser = Json2csvStreamParser; import { flatten, unwind } from "//cdn.jsdelivr.net/gh/juanjoDiaz/json2csv@7.0.7/dist/cdn/transforms/index.js"; window.Json2csvTransforms = { flatten, unwind }; ``` -------------------------------- ### json2csv CLI Usage and Options Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/cli/README.md This section outlines the available command-line options for the json2csv tool. It details parameters for input/output files, data selection, formatting, and advanced features like unwinding and flattening. ```bash Usage: json2csv [options] Options: -V, --version output the version number -i, --input Path and name of the incoming json file. Defaults to stdin. -o, --output Path and name of the resulting csv file. Defaults to stdout. -c, --config Specify a file with a valid JSON configuration. -n, --ndjson Treat the input as NewLine-Delimited JSON. -s, --no-streaming Process the whole JSON array in memory instead of doing it line by line. -f, --fields List of fields to process. Defaults to field auto-detection. -v, --default-value Default value to use for missing fields. -q, --quote Character(s) to use as quote mark. Defaults to '"'. -Q, --escaped-quote Character(s) to use as a escaped quote. Defaults to a double `quote`, '""'. -d, --delimiter Character(s) to use as delimiter. Defaults to ','. (default: ",") -e, --eol Character(s) to use as End-of-Line for separating rows. Defaults to '\n'. (default: "\n") -E, --excel-strings Wraps string data to force Excel to interpret it as string even if it contains a number. -H, --no-header Disable the column name header. -a, --include-empty-rows Includes empty rows in the resulting CSV output. -b, --with-bom Includes BOM character at the beginning of the CSV. -p, --pretty Print output as a pretty table. Use only when printing to console. --unwind [paths] Creates multiple rows from a single JSON document similar to MongoDB unwind. --unwind-blank When unwinding, blank out instead of repeating data. Defaults to false. (default: false) --flatten-objects Flatten nested objects. Defaults to false. (default: false) --flatten-arrays Flatten nested arrays. Defaults to false. (default: false) --flatten-separator Flattened keys separator. Defaults to '.'. (default: ".") -h, --help output usage information ``` -------------------------------- ### json2csv: Input from stdin, data selection, output to stdout Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/cli/README.md Shows how to pipe JSON data into json2csv via standard input, select specific fields, and display the resulting CSV on standard output. It includes instructions on how to terminate stdin input. ```bash $ json2csv -f price [{"price":1000},{"price":2000}] Hit Enter and afterwards CTRL + D to end reading from stdin. The terminal should show price 1000 2000 ``` -------------------------------- ### Unwind Transform Options for Arrays Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/transforms.md These JavaScript examples illustrate the usage of the `unwind` transform from '@json2csv/transforms'. They show how to unwind a single field and how to do the same while also blanking out repeated data for enhanced CSV formatting. ```javascript // Unwind a single field unwind({ paths: ['fieldToUnwind'] }); // Unwind a single field and blank out repeated data unwind({ paths: ['fieldToUnwind'], blankOut: true }); ``` -------------------------------- ### Asynchronous CSV Parsing with WHATWGAsyncParser Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/whatwg-async-parser.md Demonstrates how to use the WHATWGAsyncParser to convert data into CSV format asynchronously. It shows how to initialize the parser, process data into a stream, and either convert the stream to a promise resolving to the full CSV or pipe the stream to a writable destination. ```javascript import { AsyncParser } from '@json2csv/whatwg'; const opts = {}; const transformOpts = {}; const asyncOpts = {}; const parser = new AsyncParser(opts, asyncOpts, transformOpts); const csv = await parser.parse(data).promise(); // The parse method return the stream transform readable side. // So data can be passed to a writable stream (a file, http request, etc.) parser.parse(data).pipeTo(writableStream); ``` -------------------------------- ### Import WHATWGAsyncParser from CDN (Latest) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/whatwg-async-parser.md Loads the latest version of json2csv WHATWGAsyncParser directly in the browser using an ES6 module import from a CDN. This requires the browser to support modules. ```html ``` -------------------------------- ### Custom Transform Function in JavaScript Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/transforms.md These JavaScript examples showcase how to create custom transforms for the json2csv library. It provides both standard function and ES6 arrow function syntax for defining a transform that can modify or create new items. ```javascript function doNothing(item) { // apply tranformations or create new object return transformedItem; } // or using ES6 const doNothing = (item) => { // apply tranformations or create new object return transformedItem; }; ``` -------------------------------- ### Parameterized Custom String Formatter (JavaScript) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/formatters.md Creates custom string formatters that can be parameterized, such as limiting string length. This example demonstrates creating a formatter that clips strings and optionally adds an ellipsis, using a factory function for parameterization. ```javascript const fixedLengthStringFormatter = (stringLength, ellipsis = '...') => (item) => item.length <= stringLength ? item : `${item.slice(0, stringLength - ellipsis.length)}${ellipsis}`; // Example usage: // { string: fixedLengthStringFormatter(20) } // { string: fixedLengthStringFormatter(20, '') } ``` -------------------------------- ### Import json2csv WHATWG modules from CDN (specific version) Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/whatwg/README.md Imports specific versions of the AsyncParser and TransformStream modules from the @json2csv/whatwg package via a CDN. This allows for precise version control in browser-based projects. ```html ``` -------------------------------- ### Import json2csv parser via CDN (specific version) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/parser.md Loads a specific version (e.g., 7.0.7) of the json2csv parser from a CDN. This allows for version control and ensures compatibility with other project dependencies. ```html ``` -------------------------------- ### Custom Function Formatter (JavaScript) Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/formatters.md Defines custom functions for formatting specific data types. These functions take an item as input and return the formatted string. Examples include formatting functions by name or creating fixed-length strings. ```javascript function formatType(itemOfType) { // format type return formattedItem; } const formatType = (itemOfType) => { // format type return itemOfType; }; const functionNameFormatter = (item) => item.name || 'unknown'; ``` -------------------------------- ### Import json2csv WHATWG modules from CDN (latest) Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/whatwg/README.md Imports the AsyncParser and TransformStream modules from the @json2csv/whatwg package hosted on a CDN. This is suitable for direct use in browsers that support ES6 modules. ```html ``` -------------------------------- ### WHATWG Transform Stream for JSON to CSV Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/transforms.md This snippet demonstrates how to use the WHATWG TransformStream API for converting JSON data to CSV. It requires the '@json2csv/whatwg' and '@json2csv/transforms' packages. The example shows piping data through a transform stream with an unwind transformation. ```javascript import { TransformStream } from '@json2csv/whatwg'; import { unwind } from '@json2csv/transforms'; const opts = { transforms: [ unwind({ paths: ['colors'] }) ] }; const parser = new TransformStream(opts); await sourceStream.pipeThrough(parser).pipeTo(writableStream); ``` -------------------------------- ### Convert JSON to CSV using CLI Source: https://github.com/juanjodiaz/json2csv/blob/main/packages/cli/README.md Demonstrates the basic usage of the json2csv CLI tool to convert a JSON file ('input.json') into CSV format. The output is typically printed to standard output or can be redirected. ```bash json2csv -i input.json ``` -------------------------------- ### Import StreamParser via CDN Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/parsers/stream-parser.md Shows how to import the StreamParser directly into a web page using a CDN, packaged as an ES6 module. This allows for using the streaming functionality in browser-based applications without a build process. ```html ``` ```html ``` -------------------------------- ### WHATWG Transform Stream for JSON to CSV Conversion Source: https://github.com/juanjodiaz/json2csv/blob/main/docs/advanced-options/data-selection.md Implements JSON to CSV conversion using the WHATWG TransformStream API, suitable for modern web environments and Node.js. This example demonstrates stream piping and collection of the resulting CSV data. ```javascript import { TransformStream } from '@json2csv/whatwg'; const data = [ { "carModel": "Audi", "price": 0, "color": "blue" }, { "carModel": "BMW", "price": 15000, "color": "red", "manual": true }, { "carModel": "Mercedes", "price": 20000, "color": "yellow" }, { "carModel": "Porsche", "price": 30000, "color": "green" } ]; const dataStream = new ReadableStream({ start(controller) { data.forEach(record => controller.enqueue(record)); controller.close(); } }); const opts = { fields: [ { label: 'Car Model', value: 'carModel' }, { label: 'Price', value: (record) => new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(record.price) }, { label: 'Color', value: 'color' }, { label: 'Manual', value: 'manual', default: false } ] }; const json2csvParserStream = new TransformStream(opts); let csv = ''; const toTextStream = new WritableStream({ write(chunk) { csv += chunk; } }); await dataStream.pipeThrough(json2csvParserStream).pipeTo(toTextStream); console.log(csv); ```