### CLI Configuration File Example Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This is an example of a JSON configuration file used with the `json2csv` CLI. It defines fields (including nested ones and custom labels), delimiter, quoting, header inclusion, end-of-line characters, and array unwinding options. ```json { "fields": [ "id", { "label": "Full Name", "value": "name" }, { "label": "Email Address", "value": "email" }, "address.city" ], "delimiter": ";", "quote": "\"", "header": true, "eol": "\n", "unwind": ["tags"], "defaultValue": "N/A" } ``` -------------------------------- ### Provide Default Values for Missing Fields with @json2csv Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This example demonstrates how to handle missing or undefined fields in JSON data by providing default values. The 'default' option within the 'fields' configuration of @json2csv is used. ```javascript import { Parser } from '@json2csv/plainjs'; const data = [ { name: 'John', age: 30, city: 'New York', phone: '123-456-7890' }, { name: 'Jane', age: 25 }, // Missing city and phone { name: 'Bob', city: 'Los Angeles' } // Missing age and phone ]; const opts = { fields: [ 'name', { label: 'Age', value: 'age', default: 'N/A' }, { label: 'City', value: 'city', default: 'Unknown' }, { label: 'Phone', value: 'phone', default: 'Not provided' } ] }; const parser = new Parser(opts); const csv = parser.parse(data); /* Output: "name","Age","City","Phone" "John",30,"New York","123-456-7890" "Jane",25,"Unknown","Not provided" "Bob","N/A","Los Angeles","Not provided" */ ``` -------------------------------- ### CLI: Specify Fields and Nested Fields Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt These examples show how to select specific fields and access nested JSON properties for CSV export using the json2csv CLI. The `-f` flag is used for field selection, supporting dot notation for nested structures. ```bash # Specify fields to include json2csv -i data.json -f "name,email,age" -o output.csv # Nested field selection json2csv -i data.json -f "id,user.name,user.email,address.city" -o output.csv ``` -------------------------------- ### Convert NDJSON to CSV with @json2csv/node Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This example shows how to convert Newline Delimited JSON (NDJSON) files to CSV format using streams. It pipes data from a readable stream through the 'ndjson' parser and then @json2csv/node's Transform stream. ```javascript import { createReadStream, createWriteStream } from 'fs'; import { Transform } from '@json2csv/node'; import { parse } from 'ndjson'; // Process NDJSON file streaming const input = createReadStream('events.ndjson', { encoding: 'utf8' }); const output = createWriteStream('events.csv', { encoding: 'utf8' }); const opts = { fields: [ 'timestamp', 'event_type', 'user_id', { label: 'Event Data', value: (row) => JSON.stringify(row.data) } ] }; input .pipe(parse()) .pipe(new Transform(opts)) .pipe(output) .on('finish', () => console.log('NDJSON conversion complete')); ``` -------------------------------- ### TypeScript JSON to CSV Conversion with Types Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt Demonstrates type-safe JSON to CSV conversion using TypeScript. It defines interfaces for input data and the desired CSV export structure, allowing for compile-time checks. The example uses the `@json2csv/plainjs` parser to transform an array of employee objects into a CSV string. ```typescript import { Parser } from '@json2csv/plainjs'; interface Employee { id: number; firstName: string; lastName: string; email: string; department: string; salary: number; hireDate: string; } interface EmployeeExport { 'Employee ID': number; 'Full Name': string; 'Email': string; 'Department': string; 'Annual Salary': string; } const employees: Employee[] = [ { id: 1, firstName: 'John', lastName: 'Doe', email: 'john.doe@company.com', department: 'Engineering', salary: 95000, hireDate: '2020-01-15' }, { id: 2, firstName: 'Jane', lastName: 'Smith', email: 'jane.smith@company.com', department: 'Design', salary: 85000, hireDate: '2021-03-20' } ]; const opts = { fields: [ { label: 'Employee ID', value: 'id' }, { label: 'Full Name', value: (row: Employee) => `${row.firstName} ${row.lastName}` }, { label: 'Email', value: 'email' }, { label: 'Department', value: 'department' }, { label: 'Annual Salary', value: (row: Employee) => `$${row.salary.toLocaleString()}` } ] as const }; const parser = new Parser(opts); const csv: string = parser.parse(employees); ``` -------------------------------- ### CLI: Process NDJSON and Unwind Arrays Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt These examples cover processing newline-delimited JSON (NDJSON) files with the `--ndjson` flag and unwinding nested arrays into separate rows using the `--unwind` flag. These are powerful options for handling complex JSON structures. ```bash # Process NDJSON json2csv -i events.ndjson --ndjson -o events.csv # Unwind arrays json2csv -i data.json --unwind "tags,categories" -o output.csv ``` -------------------------------- ### CLI: Using a Configuration File Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This shows how to use a JSON configuration file with `json2csv` via the `-c` flag for complex conversion settings. This approach is beneficial for reusability and managing intricate field mappings or options. ```bash # With configuration file json2csv -i data.json -c config.json -o output.csv ``` -------------------------------- ### CLI: Stdin/Stdout and Multiple Input Files Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This demonstrates piping JSON data from standard input to `json2csv` and redirecting the output to standard output, as well as processing multiple JSON files matching a pattern into a single CSV. This is useful for scripting and batch processing. ```bash # From stdin to stdout cat data.json | json2csv -f "id,name,email" > output.csv # Multiple input files json2csv -i "data/*.json" -o combined.csv ``` -------------------------------- ### CLI: Basic JSON to CSV Conversion Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This demonstrates the basic command-line usage of json2csv to convert a JSON file to a CSV file. It specifies input and output files using `-i` and `-o` flags respectively. This is the simplest way to perform a conversion. ```bash # Basic conversion json2csv -i input.json -o output.csv ``` -------------------------------- ### CLI: No Header and Pretty Print Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This shows how to omit the header row from the output CSV using the `--no-header` flag and how to pretty-print the JSON data to the console using the `-p` flag, which is useful for quick inspections. ```bash # No header row json2csv -i data.json --no-header -o output.csv # Pretty print to console json2csv -i data.json -p ``` -------------------------------- ### JavaScript Database Export: Small & Large Datasets Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt Provides two patterns for exporting database query results to CSV using JavaScript. The first is a synchronous approach for small datasets using `writeFileSync`. The second is a streaming approach for large datasets using `createWriteStream` and the `@json2csv/node` Transform stream for efficient memory usage. ```javascript import { Parser } from '@json2csv/plainjs'; import { writeFileSync } from 'fs'; import { Transform } from '@json2csv/node'; import { createWriteStream } from 'fs'; // Synchronous approach for small datasets async function exportSmallDataset(db) { const results = await db.query(` SELECT orders.id, orders.order_date, customers.name as customer_name, customers.email, products.name as product_name, order_items.quantity, order_items.price FROM orders JOIN customers ON orders.customer_id = customers.id JOIN order_items ON orders.id = order_items.order_id JOIN products ON order_items.product_id = products.id WHERE orders.order_date >= ? `, ['2024-01-01']); const opts = { fields: [ { label: 'Order ID', value: 'id' }, { label: 'Date', value: (row) => new Date(row.order_date).toLocaleDateString() }, { label: 'Customer', value: 'customer_name' }, { label: 'Email', value: 'email' }, { label: 'Product', value: 'product_name' }, { label: 'Quantity', value: 'quantity' }, { label: 'Price', value: (row) => `$${row.price.toFixed(2)}` }, { label: 'Total', value: (row) => `$${(row.quantity * row.price).toFixed(2)}` } ] }; const parser = new Parser(opts); const csv = parser.parse(results); writeFileSync('orders-report.csv', csv); console.log(`Exported ${results.length} orders`); } // Streaming approach for large datasets async function exportLargeDataset(db) { const output = createWriteStream('large-export.csv'); const opts = { fields: ['id', 'name', 'email', 'created_at', 'status'] }; const transform = new Transform(opts); const stream = db.query('SELECT * FROM large_table').stream(); return new Promise((resolve, reject) => { stream .pipe(transform) .pipe(output) .on('finish', () => { console.log('Large export completed'); resolve(); }) .on('error', reject); }); } ``` -------------------------------- ### Browser: Export Data to CSV File Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This JavaScript function enables downloading CSV files directly from the browser using the '@json2csv/whatwg' library. It generates a Blob, creates a temporary URL, and simulates a click on an anchor tag for download. It handles potential errors during parsing or file creation. ```javascript import { Parser } from '@json2csv/whatwg'; // Function to trigger CSV download in browser function exportToCSV(data, filename = 'export.csv') { const opts = { fields: [ { label: 'ID', value: 'id' }, { label: 'Name', value: 'name' }, { label: 'Email', value: 'email' }, { label: 'Status', value: 'status' } ] }; try { const parser = new Parser(opts); const csv = parser.parse(data); // Create blob and download const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename; link.style.display = 'none'; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); } catch (err) { console.error('Export failed:', err); alert('Failed to export data'); } } // Example: Export data from API response async function fetchAndExport(apiUrl) { try { const response = await fetch(apiUrl); const data = await response.json(); exportToCSV(data, 'api-data.csv'); } catch (err) { console.error('Fetch error:', err); } } // Example: Export from user interaction document.getElementById('exportBtn').addEventListener('click', () => { const tableData = [ { id: 1, name: 'John', email: 'john@example.com', status: 'active' }, { id: 2, name: 'Jane', email: 'jane@example.com', status: 'active' } ]; exportToCSV(tableData, 'users.csv'); }); ``` -------------------------------- ### Basic JSON to CSV Conversion with @json2csv/plainjs Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt Performs a simple synchronous conversion of JSON arrays to CSV format using the '@json2csv/plainjs' package. It automatically detects fields from the input data. Error handling for conversion failures is included. ```javascript import { Parser } from '@json2csv/plainjs'; const data = [ { name: 'John Doe', age: 30, city: 'New York', salary: 75000 }, { name: 'Jane Smith', age: 25, city: 'San Francisco', salary: 85000 }, { name: 'Bob Johnson', age: 35, city: 'Los Angeles', salary: 95000 } ]; try { const parser = new Parser(); const csv = parser.parse(data); console.log(csv); /* Output: "name","age","city","salary" "John Doe",30,"New York",75000 "Jane Smith",25,"San Francisco",85000 "Bob Johnson",35,"Los Angeles",95000 */ } catch (err) { console.error('Conversion failed:', err.message); } ``` -------------------------------- ### JavaScript Data Transforms and Filtering for CSV Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt Shows how to apply data transformations and filtering before converting JSON to CSV using JavaScript. It includes inline functions for filtering active employees, capitalizing names, creating a full name field, and formatting salary. The output demonstrates the effect of these transformations. ```javascript import { Parser } from '@json2csv/plainjs'; const rawData = [ { id: 1, firstName: 'john', lastName: 'doe', status: 'active', salary: 50000 }, { id: 2, firstName: 'jane', lastName: 'smith', status: 'inactive', salary: 60000 }, { id: 3, firstName: 'bob', lastName: 'johnson', status: 'active', salary: 70000 } ]; const transforms = [ // Filter: Only active employees (item) => item.status === 'active' ? item : null, // Transform: Capitalize names (item) => ({ ...item, firstName: item.firstName.charAt(0).toUpperCase() + item.firstName.slice(1), lastName: item.lastName.charAt(0).toUpperCase() + item.lastName.slice(1) }), // Transform: Add computed field (item) => ({ ...item, fullName: `${item.firstName} ${item.lastName}` }), // Transform: Format salary (item) => ({ ...item, formattedSalary: `$${item.salary.toLocaleString()}` }) ].filter(Boolean); const opts = { fields: ['id', 'fullName', 'formattedSalary', 'status'], transforms }; const parser = new Parser(opts); const csv = parser.parse(rawData); /* Output includes only active employees with transformed data: "id","fullName","formattedSalary","status" 1,"John Doe","$50,000","active" 3,"Bob Johnson","$70,000","active" */ ``` -------------------------------- ### Express.js API: Export Users to CSV Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This snippet demonstrates how to create an Express.js API endpoint that fetches user data and exports it as a downloadable CSV file. It uses '@json2csv/plainjs' for parsing and handles content type and disposition headers. It requires Express.js and '@json2csv/plainjs'. ```javascript import express from 'express'; import { Parser } from '@json2csv/plainjs'; const app = express(); // Export users as CSV download app.get('/api/export/users', async (req, res) => { try { // Fetch data from database const users = await db.users.findAll({ where: { status: 'active' } }); const opts = { fields: [ { label: 'User ID', value: 'id' }, { label: 'Full Name', value: (row) => `${row.firstName} ${row.lastName}` }, { label: 'Email', value: 'email' }, { label: 'Registration Date', value: (row) => new Date(row.createdAt).toLocaleDateString() }, { label: 'Last Login', value: (row) => row.lastLogin || 'Never' } ] }; const parser = new Parser(opts); const csv = parser.parse(users); res.header('Content-Type', 'text/csv; charset=utf-8'); res.header('Content-Disposition', 'attachment; filename="users-export.csv"'); res.send(csv); } catch (err) { console.error('Export error:', err); res.status(500).json({ error: 'Export failed', message: err.message }); } }); // Stream large export app.get('/api/export/orders', async (req, res) => { try { const opts = { fields: ['orderId', 'customerId', 'total', 'date'] }; const transform = new Transform(opts); // Assuming Transform is imported or defined elsewhere res.header('Content-Type', 'text/csv'); res.header('Content-Disposition', 'attachment; filename="orders.csv"'); const dataStream = db.orders.stream(); // Assuming db.orders.stream() provides a readable stream dataStream.pipe(transform).pipe(res); } catch (err) { res.status(500).json({ error: err.message }); } }); app.listen(3000, () => console.log('Export API running on port 3000')); ``` -------------------------------- ### Field Selection and Custom Labels with @json2csv/plainjs Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt Demonstrates how to control which fields are exported and customize CSV column headers using '@json2csv/plainjs'. The `fields` option allows specifying desired fields and their corresponding labels in the output CSV. ```javascript import { Parser } from '@json2csv/plainjs'; const data = [ { firstName: 'John', lastName: 'Doe', email: 'john@example.com', age: 30, internal_id: 'X123' }, { firstName: 'Jane', lastName: 'Smith', email: 'jane@example.com', age: 25, internal_id: 'X456' } ]; const opts = { fields: [ { label: 'First Name', value: 'firstName' }, { label: 'Last Name', value: 'lastName' }, { label: 'Email Address', value: 'email' } ] }; const parser = new Parser(opts); const csv = parser.parse(data); /* Output: "First Name","Last Name","Email Address" "John","Doe","john@example.com" "Jane","Smith","jane@example.com" */ ``` -------------------------------- ### Stream Large JSON Datasets with @json2csv/node Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This snippet illustrates processing large JSON files efficiently using Node.js streams with @json2csv/node to minimize memory consumption. It shows a pipeline using 'stream-chain' and alternative simple piping. ```javascript import { createReadStream, createWriteStream } from 'fs'; import { Transform } from '@json2csv/node'; import { chain } from 'stream-chain'; import { parser } from 'stream-json'; import { streamArray } from 'stream-json/streamers/StreamArray'; // Process a large JSON file without loading it entirely into memory const opts = { fields: [ 'id', 'name', 'email', { label: 'Status', value: 'status', default: 'active' } ] }; const pipeline = chain([ createReadStream('large-dataset.json'), parser(), streamArray(), (data) => data.value, new Transform(opts), createWriteStream('output.csv') ]); pipeline.on('finish', () => console.log('Conversion completed')); pipeline.on('error', (err) => console.error('Stream error:', err)); // Alternative: Simple stream without parsing const input = createReadStream('data.json', { encoding: 'utf8' }); const output = createWriteStream('output.csv', { encoding: 'utf8' }); input .pipe(new Transform({ fields: ['id', 'name', 'email'] })) .pipe(output) .on('finish', () => console.log('Done')); ``` -------------------------------- ### Configure Custom Delimiters and Formatting with @json2csv Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This snippet demonstrates how to customize the CSV output using @json2csv/plainjs. It covers setting custom delimiters (like tabs for TSV), quote characters, line endings, and including a Byte Order Mark (BOM) for Excel compatibility. ```javascript import { Parser } from '@json2csv/plainjs'; import { writeFileSync } from 'fs'; const data = [ { id: 1, name: 'John', notes: 'Contains "quotes" and, commas' }, { id: 2, name: 'Jane', notes: 'Line 1\nLine 2' } ]; // TSV (Tab-Separated Values) format const tsvOpts = { fields: ['id', 'name', 'notes'], delimiter: '\t', quote: '' }; const tsvParser = new Parser(tsvOpts); const tsv = tsvParser.parse(data); writeFileSync('output.tsv', tsv); // Semicolon-delimited with single quotes const customOpts = { fields: ['id', 'name', 'notes'], delimiter: ';', quote: "'", eol: '\r\n' // Windows line endings }; const customParser = new Parser(customOpts); const custom = customParser.parse(data); // Excel-compatible with BOM const excelOpts = { fields: ['id', 'name', 'notes'], withBOM: true, delimiter: ',', eol: '\r\n' }; const excelParser = new Parser(excelOpts); const excel = '\ufeff' + excelParser.parse(data); writeFileSync('excel-export.csv', excel); ``` -------------------------------- ### Custom Value Transformations with @json2csv/plainjs Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt Shows how to apply custom functions to compute or transform field values during CSV conversion using '@json2csv/plainjs'. The `value` option within the `fields` configuration allows for dynamic data processing. ```javascript import { Parser } from '@json2csv/plainjs'; const data = [ { name: 'John', salary: 75000, hireDate: '2020-01-15', hobbies: ['reading', 'gaming'] }, { name: 'Jane', salary: 85000, hireDate: '2019-06-20', hobbies: ['painting', 'traveling', 'photography'] } ]; const opts = { fields: [ 'name', { label: 'Annual Salary', value: (row) => `$${row.salary.toLocaleString()}` }, { label: 'Monthly Salary', value: (row) => `$${(row.salary / 12).toFixed(2)}` }, { label: 'Years Employed', value: (row) => new Date().getFullYear() - new Date(row.hireDate).getFullYear() }, { label: 'Hire Date', value: (row) => new Date(row.hireDate).toLocaleDateString('en-US') }, { label: 'Hobbies', value: (row) => row.hobbies.join('; ') }, { label: 'Hobby Count', value: (row) => row.hobbies.length } ] }; const parser = new Parser(opts); const csv = parser.parse(data); /* Output includes computed values: "name","Annual Salary","Monthly Salary","Years Employed","Hire Date","Hobbies","Hobby Count" "John","$75,000","$6,250.00",5,"1/15/2020","reading; gaming",2 */ ``` -------------------------------- ### CLI: Custom Delimiter and TSV Format Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This demonstrates how to customize the delimiter for CSV files using the `-d` flag, including creating Tab Separated Values (TSV) files. This is useful for compatibility with different software that expects specific delimiters. ```bash # Custom delimiter (semicolon) json2csv -i data.json -d ";" -o output.csv # TSV format json2csv -i data.json -d "\t" -o output.tsv ``` -------------------------------- ### Nested Object Handling with @json2csv/plainjs Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt Illustrates how to access and flatten nested object properties for CSV conversion using dot notation with '@json2csv/plainjs'. The `fields` option supports specifying paths to nested values. ```javascript import { Parser } from '@json2csv/plainjs'; const data = [ { id: 1, name: 'John Doe', address: { street: '123 Main St', city: 'New York', coordinates: { lat: 40.7128, lng: -74.0060 } }, company: { name: 'Acme Corp', department: 'Engineering' } }, { id: 2, name: 'Jane Smith', address: { street: '456 Oak Ave', city: 'San Francisco', coordinates: { lat: 37.7749, lng: -122.4194 } }, company: { name: 'Tech Inc', department: 'Design' } } ]; const opts = { fields: [ 'id', 'name', 'address.street', 'address.city', { label: 'Latitude', value: 'address.coordinates.lat' }, { label: 'Longitude', value: 'address.coordinates.lng' }, { label: 'Company', value: 'company.name' }, { label: 'Department', value: 'company.department' } ] }; const parser = new Parser(opts); const csv = parser.parse(data); ``` -------------------------------- ### JavaScript CSV Export with Error Handling Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This JavaScript code defines a `CSVExporter` class that handles the conversion of JSON data to CSV format and exports it to a file. It includes validation for input data and robust error handling for both the parsing and file writing processes, returning detailed success or error objects. ```javascript import { Parser } from '@json2csv/plainjs'; import { writeFileSync } from 'fs'; class CSVExporter { constructor(options = {}) { this.defaultOptions = { fields: [], header: true, ...options }; } validate(data) { if (!Array.isArray(data)) { throw new Error('Data must be an array'); } if (data.length === 0) { throw new Error('Data array is empty'); } return true; } export(data, options = {}) { try { this.validate(data); const opts = { ...this.defaultOptions, ...options }; const parser = new Parser(opts); const csv = parser.parse(data); return { success: true, csv, rowCount: data.length }; } catch (err) { console.error('Export error:', err); return { success: false, error: err.message, code: err.code || 'EXPORT_ERROR' }; } } exportToFile(data, filename, options = {}) { const result = this.export(data, options); if (!result.success) { return result; } try { writeFileSync(filename, result.csv); return { success: true, filename, rowCount: result.rowCount }; } catch (err) { return { success: false, error: `File write error: ${err.message}`, code: 'FILE_WRITE_ERROR' }; } } } // Usage const exporter = new CSVExporter({ fields: ['id', 'name', 'email'] }); const result = exporter.exportToFile(data, 'output.csv'); if (result.success) { console.log(`Exported ${result.rowCount} rows to ${result.filename}`); } else { console.error(`Export failed: ${result.error}`); } ``` -------------------------------- ### Flatten Array Fields to Multiple Rows with @json2csv Source: https://context7.com/context7/juanjodiaz_github_io_json2csv/llms.txt This snippet shows how to flatten array fields in JSON data, creating multiple rows in the CSV output for each item in the array. It utilizes the 'unwind' option in @json2csv. ```javascript import { Parser } from '@json2csv/plainjs'; const data = [ { customer: 'John Doe', orderId: 'ORD-001', items: ['Laptop', 'Mouse', 'Keyboard'] }, { customer: 'Jane Smith', orderId: 'ORD-002', items: ['Monitor', 'HDMI Cable'] } ]; const opts = { fields: ['customer', 'orderId', 'items'], unwind: ['items'] }; const parser = new Parser(opts); const csv = parser.parse(data); /* Output creates one row per item: "customer","orderId","items" "John Doe","ORD-001","Laptop" "John Doe","ORD-001","Mouse" "John Doe","ORD-001","Keyboard" "Jane Smith","ORD-002","Monitor" "Jane Smith","ORD-002","HDMI Cable" */ ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.