### Install Benchmark Project Dependencies Source: https://github.com/josdejong/csv42/blob/main/benchmark/README.md This command installs the Node.js dependencies required for the benchmark project. It requires Node.js and npm to be installed. The installation process populates the 'node_modules' directory. ```bash npm run install ``` -------------------------------- ### Install and Build CSV42 Library Source: https://github.com/josdejong/csv42/blob/main/benchmark/README.md These npm commands are used to install the dependencies for the csv42 library and then build it, including running tests. Requires Node.js and npm to be installed. The build process generates necessary output files for the library. ```bash npm run install npm run build-and-test ``` -------------------------------- ### Install csv42 using npm Source: https://github.com/josdejong/csv42/blob/main/README.md This command installs the csv42 library using npm, making it available for use in your JavaScript project. Ensure you have Node.js and npm installed. ```bash npm install csv42 ``` -------------------------------- ### Execute CSV Benchmark Source: https://github.com/josdejong/csv42/blob/main/benchmark/README.md This command runs the performance benchmark for the CSV parsing libraries, including csv42. It requires Node.js and npm to be installed, and the benchmark script to be defined in the project's package.json. The output will be the benchmark results. ```bash npm run benchmark ``` -------------------------------- ### Clone CSV42 Project Repository Source: https://github.com/josdejong/csv42/blob/main/benchmark/README.md This command clones the source code of the csv42 project from GitHub. It requires Git to be installed on the system. No specific input or output files are generated by this command itself. ```bash git clone https://github.com/josdejong/csv42.git ``` -------------------------------- ### Value Formatting Source: https://github.com/josdejong/csv42/blob/main/README.md Describes the `formatValue` function and provides an example of a custom `ValueFormatter`. ```APIDOC ## `formatValue(value: unknown): string` ### Description Function used to change any type of value into a serialized string for the CSV. The built-in formatter will only enclose values in quotes when necessary, and will stringify nested JSON objects. ### Method `formatValue` ### Parameters - **`value`** (unknown) - The value to format. ### Example ```ts // A simple example of a ValueFormatter that encloses every value in quotes: function formatValue(value: unknown): string { return '"' + String(value) + '"' } console.log(formatValue('hello')); // Output: "hello" console.log(formatValue(123)); // Output: "123" ``` ### Response - **`string`** - The serialized string representation of the value. ``` -------------------------------- ### Manipulate Nested Object Paths Source: https://context7.com/josdejong/csv42/llms.txt Utilities for parsing string paths into structured arrays, stringifying path arrays back into strings, and getting or setting values within nested objects. These functions are essential for dynamic data access and manipulation. ```typescript import { parsePath, stringifyPath, getIn, setIn } from 'csv42' // Parse string paths into structured Path arrays const path1 = parsePath('user.address.city') console.log(path1) // Output: ['user', 'address', 'city'] const path2 = parsePath('items[0].name') console.log(path2) // Output: ['items', 0, 'name'] const path3 = parsePath('data["property.with.dots"]') console.log(path3) // Output: ['data', 'property.with.dots'] // Stringify Path arrays back to strings const pathStr1 = stringifyPath(['user', 'profile', 'email']) console.log(pathStr1) // Output: 'user.profile.email' const pathStr2 = stringifyPath(['items', 0, 'price']) console.log(pathStr2) // Output: 'items[0].price' // Get nested values from objects const user = { id: 1, profile: { name: 'John Doe', contacts: { email: 'john@example.com', phones: ['555-0100', '555-0101'] } } } const email = getIn(user, ['profile', 'contacts', 'email']) console.log(email) // Output: 'john@example.com' const phone = getIn(user, parsePath('profile.contacts.phones[0]')) console.log(phone) // Output: '555-0100' // Set nested values in objects const emptyObj = {} setIn(emptyObj, ['user', 'address', 'city'], 'New York') setIn(emptyObj, ['user', 'address', 'zip'], '10001') setIn(emptyObj, ['user', 'tags', 0], 'admin') console.log(emptyObj) // Output: // { // user: { // address: { city: 'New York', zip: '10001' }, // tags: ['admin'] // } // } ``` -------------------------------- ### Get Nested Object Property (JavaScript) Source: https://github.com/josdejong/csv42/blob/main/README.md Retrieves a value from a nested object using a structured path. This function simplifies accessing data within complex, multi-level object structures. It takes an object and a Path object, returning the retrieved value or undefined. ```javascript function getIn(object: NestedObject, path: Path): unknown { // Implementation details for getting nested properties return /* value from object or undefined */; } ``` -------------------------------- ### Parse CSV Value String to Original Type Source: https://github.com/josdejong/csv42/blob/main/README.md This function is used within `csv2json` to parse stringified values back into their appropriate data types (e.g., numbers, booleans, strings). The provided example parses numeric strings into numbers, otherwise returning the original string. It takes the string value and a boolean indicating if the value was quoted. ```typescript function parseValue(value: string, quoted: boolean): unknown { const num = Number(value) return isNaN(num) ? value : num } ``` -------------------------------- ### Navigate to Benchmark Directory Source: https://github.com/josdejong/csv42/blob/main/benchmark/README.md This command changes the current directory to the 'benchmark' subdirectory within the cloned csv42 project. It is a standard shell command and does not have specific dependencies beyond the operating system's shell. ```bash cd ./benchmark ``` -------------------------------- ### Release New Version (Shell Script) Source: https://github.com/josdejong/csv42/blob/main/README.md Automates the process of releasing a new version of the npm package. This script handles linting, testing, building, version incrementing, Git operations (commit, tag, push), and publishing to npm. It can be run directly or with a dry-run option. ```bash #!/bin/bash npm run release # or npm run release-dry-run ``` -------------------------------- ### JavaScript CSV and JSON Conversion with csv42 Source: https://github.com/josdejong/csv42/blob/main/test-lib/playground.html This JavaScript code demonstrates how to use the csv42 library to convert between JSON and CSV formats. It utilizes functions `json2csv` and `csv2json` from the library. The code sets up event listeners to update one format when the other changes in the respective text areas. ```javascript import { json2csv, csv2json } from '../lib/esm/index.js' const jsonTextArea = document.getElementById('json') const csvTextArea = document.getElementById('csv') function initialize() { const json = [ { id: 1, name: 'Joe' }, { id: 2, name: 'Sarah' } ] const csv = json2csv(json) jsonTextArea.value = JSON.stringify(json, null, 2) csvTextArea.value = csv } function updateJSON() { const json = csv2json(csvTextArea.value) jsonTextArea.value = JSON.stringify(json, null, 2) } function updateCSV() { const json = JSON.parse(jsonTextArea.value) csvTextArea.value = json2csv(json) } jsonTextArea.addEventListener('input', updateCSV) csvTextArea.addEventListener('input', updateJSON) initialize() ``` -------------------------------- ### Type Checking Utilities with csv42 Source: https://context7.com/josdejong/csv42/llms.txt Demonstrates how to use `isObject` and `isObjectOrArray` from the csv42 library to validate data types. These functions are useful for conditional logic and custom flattening callbacks in data transformation processes. ```typescript import { isObject, isObjectOrArray } from 'csv42' // Check for plain objects (not arrays, classes, or primitives) console.log(isObject({ name: 'John' })) // Output: true console.log(isObject([1, 2, 3])) // Output: false console.log(isObject(new Date())) // Output: false console.log(isObject(null)) // Output: false // Check for objects or arrays console.log(isObjectOrArray({ name: 'John' })) // Output: true console.log(isObjectOrArray([1, 2, 3])) // Output: true console.log(isObjectOrArray('string')) // Output: false // Use in custom flatten callbacks import { json2csv } from 'csv42' const data = [ { id: 1, coords: { x: 10, y: 20 }, tags: ['a', 'b'] }, { id: 2, coords: { x: 30, y: 40 }, tags: ['c'] } ] // Flatten everything (objects and arrays) const csvAll = json2csv(data, { flatten: isObjectOrArray }) // Flatten only objects, serialize arrays as JSON const csvObjectsOnly = json2csv(data, { flatten: isObject }) console.log(csvObjectsOnly) // Output: // id,coords.x,coords.y,tags // 1,10,20,"[""a"",""b""]" // 2,30,40,"[""c""]" ``` -------------------------------- ### Error Handling and Edge Cases with csv42 Source: https://context7.com/josdejong/csv42/llms.txt Illustrates how to handle various edge cases in CSV processing using csv42, including quoted fields with special characters, null/undefined values, empty arrays, missing fields, and inconsistent columns. It demonstrates robust parsing and serialization. ```typescript import { csv2json, json2csv } from 'csv42' // Handle quoted fields with special characters const csvWithSpecial = `id,description,notes 1,"Product with, comma","Line 1 Line 2" 2,"Product with ""quotes""","Normal note" ` try { const data = csv2json(csvWithSpecial) console.log(data) // Output: // [ // { id: 1, description: 'Product with, comma', notes: 'Line 1 Line 2' }, // { id: 2, description: 'Product with "quotes"', notes: 'Normal note' } // ] } catch (error) { console.error('CSV parsing error:', error.message) } // Handle null and undefined values const dataWithNulls = [ { id: 1, name: 'John', email: 'john@example.com' }, { id: 2, name: null, email: undefined }, { id: 3, name: '', email: 'jane@example.com' } ] const csvNulls = json2csv(dataWithNulls) console.log(csvNulls) // Output: // id,name,email // 1,John,john@example.com // 2,, // 3,"",jane@example.com // Handle empty arrays and missing fields const heterogeneousData = [ { id: 1, name: 'Alice', skills: ['js', 'ts'] }, { id: 2, name: 'Bob' }, // missing skills field { id: 3, name: 'Charlie', skills: [], department: 'IT' } // empty array, extra field ] const csvHeterogeneous = json2csv(heterogeneousData) console.log(csvHeterogeneous) // All fields are preserved, missing values shown as empty // Parse CSV with inconsistent columns const csvInconsistent = `id,name 1,Alice 2,Bob,extra_value 3,Charlie` const parsedInconsistent = csv2json(csvInconsistent) console.log(parsedInconsistent) // Extra values are handled gracefully based on field configuration ``` -------------------------------- ### CSV Conversion with Custom Field Mapping - TypeScript Source: https://context7.com/josdejong/csv42/llms.txt This code snippet shows how to map and transform fields during JSON to CSV and CSV to JSON conversions. It uses `getValue` callbacks to transform JSON data to CSV fields and `setValue` callbacks to parse CSV data into JSON objects. This allows for flexible control over the structure and content of the CSV output and input. ```typescript import { json2csv, csv2json } from 'csv42' // JSON to CSV with custom field selection and transformation const products = [ { id: 1, name: 'Laptop', price: 999.99, category: 'Electronics', inStock: true }, { id: 2, name: 'Mouse', price: 29.99, category: 'Electronics', inStock: false } ] const csvCustomFields = json2csv(products, { fields: [ { name: 'product_id', getValue: (item) => item.id }, { name: 'product_name', getValue: (item) => item.name.toUpperCase() }, { name: 'price_usd', getValue: (item) => `$${item.price.toFixed(2)}` }, { name: 'available', getValue: (item) => item.inStock ? 'Yes' : 'No' } ] }) console.log(csvCustomFields) // Output: // product_id,product_name,price_usd,available // 1,LAPTOP,$999.99,Yes // 2,MOUSE,$29.99,No // CSV to JSON with custom field mapping and transformation const csvInput = `id,fullName,totalPrice 1,John Doe,150.50 2,Jane Smith,200.75` const orders = csv2json(csvInput, { fields: [ { name: 'id', setValue: (item, value) => { item.orderId = value } }, { name: 'fullName', setValue: (item, value) => { const parts = String(value).split(' ') item.firstName = parts[0] item.lastName = parts[1] }}, { name: 'totalPrice', setValue: (item, value) => { item.amount = Number(value) item.currency = 'USD' }} ] }) console.log(orders) // Output: // [ // { orderId: 1, firstName: 'John', lastName: 'Doe', amount: 150.50, currency: 'USD' }, // { orderId: 2, firstName: 'Jane', lastName: 'Smith', amount: 200.75, currency: 'USD' } // ] ``` -------------------------------- ### Configure CSV Flattening with Callbacks Source: https://context7.com/josdejong/csv42/llms.txt Control how nested data structures are flattened into columns or serialized as JSON strings during CSV conversion. This feature uses callback functions to determine flattening behavior, allowing for fine-grained control over output. ```typescript import { json2csv, isObject, isObjectOrArray } from 'csv42' const complexData = [ { id: 1, user: { name: 'John', email: 'john@example.com' }, tags: ['tag1', 'tag2'], metadata: { created: '2024-01-01', modified: '2024-01-15' } }, { id: 2, user: { name: 'Jane', email: 'jane@example.com' }, tags: ['tag3'], metadata: { created: '2024-02-01', modified: '2024-02-10' } } ] // Flatten only plain objects (default behavior) const csvDefault = json2csv(complexData) console.log(csvDefault) // Output: // id,user.name,user.email,tags,metadata.created,metadata.modified // 1,John,john@example.com,"[""tag1"",""tag2""]",2024-01-01,2024-01-15 // 2,Jane,jane@example.com,"[""tag3""]",2024-02-01,2024-02-10 // Flatten both objects and arrays const csvFlattenAll = json2csv(complexData, { flatten: isObjectOrArray }) console.log(csvFlattenAll) // Output will include flattened array indices like tags[0], tags[1] // Custom flatten logic - only flatten specific fields const csvCustomFlatten = json2csv(complexData, { flatten: (value) => { // Only flatten objects that have a 'name' property return isObject(value) && 'name' in (value as object) } }) console.log(csvCustomFlatten) // Output: // id,user.name,user.email,tags,metadata // 1,John,john@example.com,"[""tag1"",""tag2""]","{ ``` -------------------------------- ### Collect Nested Paths from Data Source: https://context7.com/josdejong/csv42/llms.txt Automatically discover all unique nested paths within a dataset, which is useful for dynamically generating CSV fields. The `collectNestedPaths` function traverses data structures and returns an array of path arrays. ```typescript import { collectNestedPaths, isObject } from 'csv42' // Discover all fields in heterogeneous data const mixedData = [ { id: 1, name: 'Product A', details: { weight: 100, color: 'red' } }, { id: 2, name: 'Product B', details: { weight: 200, size: 'large' }, extra: 'info' }, { id: 3, name: 'Product C', tags: ['tag1', 'tag2'] } ] const paths = collectNestedPaths(mixedData, isObject) console.log(paths) // Output: // [ // ['id'], // ['name'], // ['details', 'weight'], // ['details', 'color'], // ['details', 'size'], // ['extra'], // ['tags'] // ] // Use collected paths to create custom field mappings import { json2csv, stringifyPath } from 'csv42' const fields = paths.map(path => ({ name: stringifyPath(path), getValue: (item) => { let value = item for (const key of path) { value = value?.[key] if (value === undefined) break } return value } })) const csv = json2csv(mixedData, { fields }) console.log(csv) // Output includes all discovered fields with proper handling of missing values ``` -------------------------------- ### Convert JSON to CSV with csv42 Source: https://github.com/josdejong/csv42/blob/main/README.md Demonstrates converting an array of JavaScript objects into a CSV string using the `json2csv` function from the csv42 library. It shows default behavior with nested object flattening and options to disable flattening or customize field mapping. ```typescript import { json2csv } from 'csv42' const users = [ { id: 1, name: 'Joe', address: { city: 'New York', street: '1st Ave' } }, { id: 2, name: 'Sarah', address: { city: 'Manhattan', street: 'Spring street' } } ] // By default, nested JSON properties are flattened const csv = json2csv(users) console.log(csv) // id,name,address.city,address.street // 1,Joe,New York,1st Ave // 2,Sarah,Manhattan,Spring street // You can turn off flattening using the option `flatten` const csvFlat = json2csv(users, { flatten: false }) console.log(csvFlat) // id,name,address // 1,Joe,"{""city"":""New York"",""street"":""1st Ave""}" // 2,Sarah,"{""city"":""Manhattan"",""street"":""Spring street""}" // The CSV output can be fully customized and transformed using `fields`: const csvCustom = json2csv(users, { fields: [ { name: 'name', getValue: (item) => item.name }, { name: 'address', getValue: (item) => item.address.city + ' - ' + object.address.street } ] }) console.log(csvCustom) // name,address // Joe,New York - 1st Ave // Sarah,Manhattan - Spring street ``` -------------------------------- ### csv2json - Convert CSV to JSON Source: https://context7.com/josdejong/csv42/llms.txt Parses CSV strings into JavaScript objects. It supports automatic type detection, nested object reconstruction, and custom delimiters. ```APIDOC ## csv2json - Convert CSV to JSON ### Description Parse CSV strings into JavaScript objects with automatic type detection and support for nested object reconstruction. ### Method `csv2json(csvString: string, options?: object) => object[]` ### Parameters #### Request Body - **csvString** (string) - Required - The CSV string to parse. - **options** (object) - Optional - Configuration options for the parsing. - **nested** (boolean) - Optional - If true (default), reconstructs nested objects from dot-notation keys. If false, keeps keys as is. - **delimiter** (string) - Optional - The delimiter character used in the CSV. Defaults to `,`. - **header** (boolean) - Optional - If true (default), uses the first row as headers. If false, assigns generic field names like `Field 0`, `Field 1`. ### Request Example ```javascript import { csv2json } from 'csv42' // Basic CSV parsing with nested path reconstruction const csv = `id,name,age,address.city,address.zip 1,Joe,30,New York,10001 2,Sarah,25,Manhattan,10002` const users = csv2json(csv) console.log(users) // Parse without creating nested objects const usersFlat = csv2json(csv, { nested: false }) console.log(usersFlat) // Parse CSV without headers const csvNoHeader = `1,Joe,30 2,Sarah,25` const records = csv2json(csvNoHeader, { header: false }) console.log(records) // Custom delimiter parsing const tsvData = `id\tname\tcity 1\tJoe\tNew York 2\tSarah\tManhattan` const tsvRecords = csv2json(tsvData, { delimiter: '\t' }) console.log(tsvRecords) ``` ### Response #### Success Response (200) - **jsonArray** (Array) - An array of JavaScript objects parsed from the CSV string. ``` -------------------------------- ### Convert JSON to CSV with csv42 Source: https://context7.com/josdejong/csv42/llms.txt Converts an array of JSON objects to a CSV string using the `json2csv` function. Supports automatic field detection, flattening of nested objects into dot-notation, or serializing them as JSON strings. Allows customization of delimiters, line endings, and header inclusion. ```typescript import { json2csv } from 'csv42' // Basic conversion with nested objects (default behavior: flattens nested objects) const users = [ { id: 1, name: 'Joe', age: 30, address: { city: 'New York', zip: '10001' } }, { id: 2, name: 'Sarah', age: 25, address: { city: 'Manhattan', zip: '10002' } } ] const csv = json2csv(users) console.log(csv) // Convert without flattening (nested objects as JSON strings) const csvNoFlatten = json2csv(users, { flatten: false }) console.log(csvNoFlatten) // Custom delimiter and line endings const csvCustom = json2csv(users, { delimiter: ';', eol: '\n', header: true }) console.log(csvCustom) ``` -------------------------------- ### Convert CSV to JSON with csv42 Source: https://github.com/josdejong/csv42/blob/main/README.md Illustrates parsing a CSV string into an array of JavaScript objects using the `csv2json` function from the csv42 library. It covers default behavior for creating nested JSON objects from dot-notation fields and options to disable nesting or customize field mapping. ```typescript import { csv2json } from 'csv42' const csv = `id,name,address.city,address.street 1,Joe,New York,1st Ave 2,Sarah,Manhattan,Spring street` // By default, fields containing a dot will be parsed inty nested JSON objects const users = csv2json(csv) console.log(users) // [ // { id: 1, name: 'Joe', address: { city: 'New York', street: '1st Ave' } }, // { id: 2, name: 'Sarah', address: { city: 'Manhattan', street: 'Spring street' } } // ] // Creating nested objects can be turned off using the option `nested` const usersFlat = csv2json(csv, { nested: false }) console.log(usersFlat) // [ // { id: 1, name: 'Joe', 'address.city': 'New York', 'address.street': '1st Ave' }, // { id: 2, name: 'Sarah', 'address.city': 'Manhattan', 'address.street': 'Spring street' } // ] // The JSON output can be customized using `fields` const usersCustom = csv2json(csv, { fields: [ { name: 'name', setValue: (item, value) => (item.name = value) }, { name: 'address.city', setValue: (item, value) => (item.city = value) } ] }) console.log(usersCustom) // [ // { name: 'Joe', city: 'New York' }, // { name: 'Sarah', city: 'Manhattan' } // ] ``` -------------------------------- ### Format Value to CSV String Source: https://github.com/josdejong/csv42/blob/main/README.md This function serializes any given value into a string suitable for CSV. It ensures values are quoted when necessary and stringifies nested JSON objects. The default implementation encloses all values in double quotes. ```typescript function formatValue(value: unknown): string { return '"' + String(value) + '"' } ``` -------------------------------- ### Stringify Path Object (JavaScript) Source: https://github.com/josdejong/csv42/blob/main/README.md Converts a structured path object back into its string representation (e.g., 'items[3].name'). This is the inverse operation of `parsePath` and is useful for displaying or referencing paths. It takes a Path object and returns a string. ```javascript function stringifyPath(path: Path): string { // Implementation details for stringifying path objects return /* path string */; } ``` -------------------------------- ### json2csv Function Source: https://github.com/josdejong/csv42/blob/main/README.md Converts an array of JSON objects into a CSV string. Supports various options for customization. ```APIDOC ## json2csv(json: T[], options?: CsvOptions) : string ### Description Converts an array of JSON objects into a CSV formatted string. This function allows for extensive customization through the `options` parameter. ### Method N/A (This is a function, not an HTTP endpoint) ### Parameters #### Parameters - **json** (T[]) - Required - An array of JSON objects to convert. - **options** (CsvOptions) - Optional - An object containing configuration options for the CSV conversion. ##### `CsvOptions` Properties: - **header** (boolean) - Optional - If true, a header row will be included in the CSV output. Defaults to `false`. - **delimiter** (string) - Optional - The delimiter character to use between CSV fields. Defaults to `,`. - **eol** (string) - Optional - The end-of-line character sequence. Can be `\r\n` (default) or `\n`. - **flatten** (boolean or (value: unknown) => boolean) - Optional - Controls how nested objects and arrays are handled. If `true` (default), plain nested objects are flattened into multiple columns, and arrays/classes are serialized into a single field. If `false`, nested objects are serialized as JSON strings. A custom callback function can be provided for more granular control. Not applicable when `fields` is defined. - **fields** (CsvField[] or CsvFieldsParser) - Optional - An array or parser function to specify which fields to include in the CSV, their order, and any transformations. This option overrides the `flatten` behavior. ### Request Example ```javascript const jsonData = [ { "name": "Alice", "age": 30 }, { "name": "Bob", "age": 25 } ]; const csvString = json2csv(jsonData, { header: true, delimiter: ';' }); console.log(csvString); ``` ### Response #### Success Response - **string** - The CSV formatted string. ``` -------------------------------- ### Create CSV Value Formatter Function (JavaScript) Source: https://github.com/josdejong/csv42/blob/main/README.md Creates a function that stringifies a value into a valid CSV format, handling necessary escaping. This function is useful as a default for the `formatValue` option in CSV processing libraries. It takes a delimiter string as input and returns a formatter function. ```javascript function createFormatValue(delimiter: string): (value: unknown) => string { // Implementation details for formatting values with escaping return (value: unknown): string => { // ... formatting logic ... }; } ``` -------------------------------- ### csv2json Source: https://github.com/josdejong/csv42/blob/main/README.md Converts a CSV string into an array of JSON objects. Supports various options for parsing, including headers, delimiters, nested objects, and custom field extraction. ```APIDOC ## `csv2json(csv: string, options?: JsonOptions) : T[]` ### Description Converts a CSV string into an array of JSON objects. ### Method `csv2json` ### Parameters #### Options - **`header`** (boolean) - Optional - Should be set `true` when the first line of the CSV file contains a header. - **`delimiter`** (string) - Optional - Default delimiter is `,`. A delimiter must be a single character. - **`nested`** (boolean) - Optional - If `true` (default), field names containing a dot will be parsed into nested JSON objects. The option `nested` is not applicable when `fields` is defined. - **`fields`** (JsonField[] or JsonFieldsParser) - Optional - A list with fields to be extracted from the CSV file into JSON. This allows specifying which fields are include/excluded, and how they will be put into the JSON object. A field can be specified either by name, like `{ name, setValue }`, or by the index of the columns in the CSV file, like `{ index, setValue }`. - **`parseValue`** (ValueParser) - Optional - Used to parse a stringified value into a value again (number, boolean, string, ...). The build in parser will parse numbers and booleans, and will parse stringified JSON objects. ### Example ```ts // Example usage of csv2json const csvData = "name,age\nAlice,30\nBob,25"; const jsonData = csv2json<{ name: string, age: number }>(csvData, { header: true, parseValue: (value) => { const num = Number(value); return isNaN(num) ? value : num; }}); console.log(jsonData); /* [{"name":"Alice","age":30},{"name":"Bob","age":25}] */ ``` ### Response - **`T[]`** - An array of JSON objects parsed from the CSV data. ``` -------------------------------- ### Collect Nested Object Paths (JavaScript) Source: https://github.com/josdejong/csv42/blob/main/README.md Iterates over an array of nested objects to collect all possible nested paths. This is useful for generating a complete list of fields or headers for CSV export. It can optionally recurse into nested structures. It takes an array of objects and a boolean for recursion, returning an array of paths. ```javascript function collectNestedPaths(records: NestedObject[], recurse: boolean): Path[] { // Implementation details for collecting paths from nested objects return /* array of Path objects */; } ``` -------------------------------- ### Parse Path String (JavaScript) Source: https://github.com/josdejong/csv42/blob/main/README.md Converts a string representation of a nested path (e.g., 'items[3].name') into a structured path object. This utility is essential for navigating and accessing deeply nested properties within objects. It takes a path string and returns a Path object. ```javascript function parsePath(pathStr: string): Path { // Implementation details for parsing path strings return /* Path object */; } ``` -------------------------------- ### Convert CSV to JSON with csv42 Source: https://context7.com/josdejong/csv42/llms.txt Parses CSV strings into JavaScript objects using the `csv2json` function. It supports automatic type detection, reconstruction of nested objects from dot-notation keys, and handling of CSVs without headers. Custom delimiters and options for nested object creation can be specified. ```typescript import { csv2json } from 'csv42' // Basic CSV parsing with nested path reconstruction const csv = `id,name,age,address.city,address.zip 1,Joe,30,New York,10001 2,Sarah,25,Manhattan,10002` const users = csv2json(csv) console.log(users) // Parse without creating nested objects const usersFlat = csv2json(csv, { nested: false }) console.log(usersFlat) // Parse CSV without headers const csvNoHeader = `1,Joe,30 2,Sarah,25` const records = csv2json(csvNoHeader, { header: false }) console.log(records) // Custom delimiter parsing const tsvData = `id\tname\tcity 1\tJoe\tNew York 2\tSarah\tManhattan` const tsvRecords = csv2json(tsvData, { delimiter: '\t' }) console.log(tsvRecords) ``` -------------------------------- ### json2csv - Convert JSON to CSV Source: https://context7.com/josdejong/csv42/llms.txt Converts an array of JSON objects to CSV format. It supports automatic field detection and nested object flattening or serialization as JSON strings. ```APIDOC ## json2csv - Convert JSON to CSV ### Description Converts an array of JSON objects to CSV format with automatic field detection and nested object support. ### Method `json2csv(data: object[], options?: object) => string` ### Parameters #### Request Body - **data** (Array) - Required - An array of JSON objects to convert. - **options** (object) - Optional - Configuration options for the conversion. - **flatten** (boolean) - Optional - If true (default), flattens nested objects into dot-notation columns. If false, serializes nested objects as JSON strings. - **delimiter** (string) - Optional - The delimiter character for CSV fields. Defaults to `,`. - **eol** (string) - Optional - The end-of-line character. Defaults to `\n`. - **header** (boolean) - Optional - If true, includes a header row. Defaults to `true`. ### Request Example ```javascript import { json2csv } from 'csv42' const users = [ { id: 1, name: 'Joe', age: 30, address: { city: 'New York', zip: '10001' } }, { id: 2, name: 'Sarah', age: 25, address: { city: 'Manhattan', zip: '10002' } } ] // Basic conversion with nested objects (default behavior: flattens nested objects) const csv = json2csv(users) console.log(csv) // Convert without flattening (nested objects as JSON strings) const csvNoFlatten = json2csv(users, { flatten: false }) console.log(csvNoFlatten) // Custom delimiter and line endings const csvCustom = json2csv(users, { delimiter: ';', eol: '\n', header: true }) console.log(csvCustom) ``` ### Response #### Success Response (200) - **csvString** (string) - The generated CSV string. ``` -------------------------------- ### Custom Value Formatting and Parsing - TypeScript Source: https://context7.com/josdejong/csv42/llms.txt This code demonstrates the use of custom value formatting and parsing functions in the csv42 library. `formatValue` is used to serialize special data types (like Dates and Arrays) and handle string escaping for JSON to CSV conversion. `parseValue` is used to deserialize CSV data, enabling custom type conversions and parsing of specific formats (like prices, booleans, and key-value pairs) during CSV to JSON conversion. ```typescript import { json2csv, csv2json, createFormatValue } from 'csv42' // Custom value formatter for JSON to CSV const data = [ { id: 1, date: new Date('2024-01-15'), tags: ['urgent', 'important'] }, { id: 2, date: new Date('2024-02-20'), tags: ['normal'] } ] const csvFormatted = json2csv(data, { formatValue: (value) => { if (value instanceof Date) { return value.toISOString().split('T')[0] } if (Array.isArray(value)) { return '"' + value.join(';') + '"' } if (typeof value === 'string' && /[,"\r\n]/.test(value)) { return '"' + value.replace(/"/g, '""') + '"' } return String(value ?? '') } }) console.log(csvFormatted) // Output: // id,date,tags // 1,2024-01-15,"urgent;important" // 2,2024-02-20,normal // Custom value parser for CSV to JSON const csvData = `id,price,active,metadata 1,99.50,yes,key1:value1 2,150.00,no,key2:value2` const parsed = csv2json(csvData, { parseValue: (value, quoted) => { // Parse prices if (/^\d+\.\d{2}$/.test(value)) { return parseFloat(value) } // Parse yes/no as boolean if (value === 'yes') return true if (value === 'no') return false // Parse key:value pairs if (value.includes(':')) { const [key, val] = value.split(':') return { [key]: val } } // Default parsing return isNaN(Number(value)) ? value : Number(value) } }) console.log(parsed) // Output: // [ // { id: 1, price: 99.50, active: true, metadata: { key1: 'value1' } }, // { id: 2, price: 150.00, active: false, metadata: { key2: 'value2' } } // ] ``` -------------------------------- ### Parse CSV String Value (JavaScript) Source: https://github.com/josdejong/csv42/blob/main/README.md Parses a string representation of a CSV value into its appropriate data type (e.g., numbers to numbers). This function is the default for the `parseValue` option and handles type inference. It takes a string as input and returns an unknown type. ```javascript function parseValue(value: string): unknown { // Implementation details for parsing string values into appropriate types return /* parsed value */; } ``` -------------------------------- ### Set Nested Object Property (JavaScript) Source: https://github.com/josdejong/csv42/blob/main/README.md Sets or updates a value within a nested object using a structured path. This function allows for modification of deeply nested properties, creating intermediate objects if they don't exist. It takes an object, a Path, and a value, returning the modified object. ```javascript function setIn(object: NestedObject, path: Path, value: unknown): NestedObject { // Implementation details for setting nested properties return /* modified object */; } ``` -------------------------------- ### Parse CSV String to JSON Array Source: https://github.com/josdejong/csv42/blob/main/README.md Converts a CSV string into an array of JSON objects. Options allow for header detection, custom delimiters, nested object parsing, field selection, and custom value parsing. The `parseValue` option is used to convert string representations back into their original data types. ```typescript function csv2json(csv: string, options?: JsonOptions) : T[] ``` -------------------------------- ### Check if Value is Object or Array (JavaScript) Source: https://github.com/josdejong/csv42/blob/main/README.md Determines if a given value is either a plain JavaScript object or an array. This function is broader than `isObject` and is useful when operations apply to both objects and arrays. It takes an unknown value and returns a boolean. ```javascript function isObjectOrArray(value: unknown): boolean { // Implementation details for checking objects or arrays return /* true if object or array, false otherwise */; } ``` -------------------------------- ### Check if Value is Plain Object (JavaScript) Source: https://github.com/josdejong/csv42/blob/main/README.md Determines if a given value is a plain JavaScript object. This function distinguishes between objects, primitive types, arrays, and class instances. It's useful for conditional logic, particularly in data flattening operations. It takes an unknown value and returns a boolean. ```javascript function isObject(value: unknown): boolean { // Implementation details for checking plain objects return /* true if plain object, false otherwise */; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.