### Install Papa Parse with npm Source: https://github.com/mholt/papaparse/blob/master/README.md Install the papaparse library using npm. This is the recommended way to add it to your project if you are using a module bundler. ```shell npm install papaparse ``` -------------------------------- ### Parse Result Data Example (header: true) Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html When header is true, the 'data' property is an array of objects, with keys corresponding to the header row. ```json [ { "Column 1": "foo", "Column 2": "bar", "Column 1": "foo1", }, { "Column 1": "abc", "Column 2": "def", "Column 1": "abc1", } ] ``` -------------------------------- ### Parse Result Data Example (header: false) Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html When header is false, the 'data' property is an array of arrays, where each inner array represents a row. ```json [ ["Column 1", "Column 2"], ["foo", "bar"], ["abc", "def"] ] ``` -------------------------------- ### Papa Parse Error Object Example Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Example structure of an error object returned by Papa Parse. Mismatched fields will not break parsing. ```javascript // Example error: { type: "FieldMismatch", code: "TooManyFields", message: "Expected 3 fields, but parsed 4", row: 1 } ``` -------------------------------- ### Parsing with Configuration Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Parse a CSV string using an optional configuration object. ```javascript var results = Papa.parse(csvString, config); /* results = { data: [ ... ], // parsed data errors: [ ... ], // errors encountered meta: { ... } // extra parse info } */ ``` -------------------------------- ### Default Unparse Configuration Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Provides a comprehensive list of all available configuration options for the `unparse` function, including delimiter, newline characters, quoting, header inclusion, and skipping empty lines. ```javascript { quotes: false, //or array of booleans quoteChar: '"', escapeChar: '"', delimiter: ",", header: true, newline: "\r\n", skipEmptyLines: false, //other option is 'greedy', meaning skip delimiters, quotes, and whitespace. columns: null //or array of strings } ``` -------------------------------- ### Downloading and Parsing Remote Files Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Download a file from a URL and parse it using a callback. ```javascript Papa.parse("http://example.com/file.csv", { download: true, complete: function(results) { console.log(results); } }); ``` -------------------------------- ### Define download request headers Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Use this option to provide custom headers for download requests, such as authorization tokens. ```javascript downloadRequestHeaders: { 'Authorization': 'token 123345678901234567890', } ``` -------------------------------- ### Enable Web Worker Support Source: https://context7.com/mholt/papaparse/llms.txt Offload parsing to a background thread using the worker option to keep the UI responsive. Check Papa.WORKERS_SUPPORTED to verify environment compatibility. ```javascript // Parse in a web worker Papa.parse(largeFile, { worker: true, // Enable web worker header: true, step: function(results) { // Called for each row (in main thread) updateProgressUI(results.data); }, complete: function(results) { console.log("Worker finished parsing"); console.log("Total rows:", results.data.length); } }); // Check if workers are supported if (Papa.WORKERS_SUPPORTED) { console.log("Web Workers available - parsing will be non-blocking"); } else { console.log("Web Workers not available - parsing will block UI"); } // Remote file with worker Papa.parse("https://example.com/huge-dataset.csv", { download: true, worker: true, header: true, complete: function(results) { // UI remained responsive during download and parse displayResults(results.data); } }); ``` -------------------------------- ### PapaParse Configuration Options Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html This section details the various configuration options available for PapaParse. These options allow for fine-grained control over how CSV data is parsed. ```APIDOC ## PapaParse Configuration Options This document outlines the various configuration options available for PapaParse to customize CSV parsing. ### `delimiter` - **Type**: string or function - **Description**: The delimiting character. If left blank, PapaParse will attempt to auto-detect from common delimiters or use `delimitersToGuess`. If a string, it can be multi-character. If a function, it must accept the input as the first parameter and return the delimiter string. Cannot be present in `Papa.BAD_DELIMITERS`. ### `newline` - **Type**: string - **Description**: The newline sequence. Auto-detected if left blank. Must be one of `\r`, `\n`, or `\r\n`. ### `quoteChar` - **Type**: string - **Description**: The character used to quote fields. Quoting is not mandatory; unquoted fields are read correctly. ### `escapeChar` - **Type**: string - **Description**: The character used to escape the `quoteChar` within a field. Defaults to `quoteChar`. If not set, the `quoteChar` is escaped by doubling it (e.g., `"column with ""quotes"" in text"`). ### `header` - **Type**: boolean - **Description**: If `true`, the first row is treated as field names. The field names are returned in `meta.fields`, and each row is an object keyed by field name. Rows with a different number of fields than the header will cause an error. Duplicate header names are automatically renamed and stored in `meta.renamedHeaders`. ### `transformHeader` - **Type**: function - **Description**: A function applied to each header. Requires `header` to be `true`. Receives the header string and its index as arguments. Available since version 5.0. ### `dynamicTyping` - **Type**: boolean or object or function - **Description**: If `true`, numeric and boolean data are converted to their respective types. Numerical values outside the range of `[-2^53, 2^53]` are not converted to preserve precision. European-formatted numbers require swapped commas and dots. Accepts an object to specify typing per column (by number or header name) or a function that returns a boolean for each field. ### `preview` - **Type**: integer - **Description**: If greater than 0, only the specified number of rows will be parsed. ### `encoding` - **Type**: string - **Description**: The encoding to use when opening local files. Must be a value supported by the FileReader API. ### `worker` - **Type**: boolean - **Description**: If `true`, uses a worker thread for parsing, keeping the page reactive but potentially slightly slower. ### `comments` - **Type**: string - **Description**: A string indicating a comment character (e.g., `#`, `//`). Lines starting with this string are skipped. ### `step` - **Type**: function - **Description**: A callback function to stream input. It receives `results` (containing `data` and `errors`) and the `parser` object. Useful for large files. `parser.abort()` can be called to stop parsing. `parser.pause()` and `parser.resume()` are available (except when using Web Workers). Example: ```javascript step: function(results, parser) { console.log("Row data:", results.data); console.log("Row errors:", results.errors); } ``` ### `complete` - **Type**: function - **Description**: A callback function executed when parsing is complete. Receives `results` and optionally the `file` object if parsing a local file. Parse results are not available in this callback when streaming. Example: ```javascript complete: function(results, file) { console.log("Parsing complete:", results, file); } ``` ### `error` - **Type**: function - **Description**: A callback function executed if FileReader encounters an error. Receives the `error` and `file` objects. ### `download` - **Type**: boolean - **Description**: If `true`, the input string is treated as a URL to download and parse. ### `downloadRequestHeaders` - **Type**: object - **Description**: An object describing headers for download requests. Example: ```javascript downloadRequestHeaders: { 'Authorization': 'token 123345678901234567890' } ``` ### `downloadRequestBody` - **Type**: any - **Description**: The value to be set as the body of a POST request when the `download` option is used. ### `skipEmptyLines` - **Type**: boolean or string ('greedy') - **Description**: If `true`, completely empty lines are skipped. If set to `'greedy'`, lines with only whitespace after parsing are also skipped. ### `chunk` - **Type**: function - **Description**: A callback function that is invoked after each chunk of data is parsed. It receives the parsed chunk as its argument. ``` -------------------------------- ### Using jQuery to Select and Parse Files Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Selects file input elements and parses their files using Papa Parse. The `parse` method accepts a configuration object with optional `before`, `error`, and `complete` callbacks to control the parsing flow and handle errors. ```javascript $"input[type=file]").parse({ config: { // base config to use for each file }, before: function(file, inputElem) { // executed before parsing each file begins; // what you return here controls the flow }, error: function(err, file, inputElem, reason) { // executed if an error occurs while loading the file, // or if before callback aborted for some reason }, complete: function() { // executed after all files are complete } }); ``` -------------------------------- ### PapaParse Streaming and Chunking Options Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Options for controlling streaming behavior, chunk processing, and pre-chunk transformations. ```APIDOC ## Streaming and Chunking Options ### `chunk` Callback - **Description**: A callback function that activates streaming after every chunk of the file is loaded and parsed. It only works with local and remote files. Do not use both `chunk` and `step` callbacks together. - **Signature**: Identical to the `step` function. ### `chunkSize` - **Description**: Overrides `Papa.LocalChunkSize` and `Papa.RemoteChunkSize`. See the [configurable](#configurable) section for usage details. ### `fastMode` - **Description**: Speeds up parsing significantly for large inputs. It only works when the input has no quoted fields. Fast mode is automatically enabled if no `"` characters appear in the input. You can force fast mode by setting it to `true` or `false`. ### `beforeFirstChunk` - **Description**: A function to execute before parsing the first chunk. Can be used with `chunk` or `step` streaming modes. The function receives the chunk about to be parsed as an argument and may return a modified chunk. Useful for stripping header lines if they fit within a single chunk. ``` -------------------------------- ### Enable Dynamic Type Conversion Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Enable `dynamicTyping: true` to automatically convert numeric and boolean data from strings. ```javascript // Converts numeric/boolean data var results = Papa.parse(csv, { dynamicTyping: true }); ``` -------------------------------- ### Configure Papa Parse Constants and Properties Source: https://context7.com/mholt/papaparse/llms.txt Access read-only constants and modify global configuration properties like chunk sizes and delimiter detection. ```javascript // Read-only constants console.log(Papa.BAD_DELIMITERS); // ["\r", "\n", "\"", "\ufeff"] console.log(Papa.RECORD_SEP); // ASCII 30 - record separator console.log(Papa.UNIT_SEP); // ASCII 31 - unit separator console.log(Papa.BYTE_ORDER_MARK); // "\ufeff" - BOM character console.log(Papa.WORKERS_SUPPORTED); // true/false // Configurable chunk sizes (in bytes) Papa.LocalChunkSize = 1024 * 1024 * 10; // 10 MB for local files Papa.RemoteChunkSize = 1024 * 1024 * 5; // 5 MB for remote files Papa.DefaultDelimiter = ','; // Fallback delimiter // Custom delimiter detection Papa.parse(csvData, { delimitersToGuess: [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP], complete: function(results) { console.log("Detected delimiter:", results.meta.delimiter); } }); ``` -------------------------------- ### Parsing Local Files Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Parse a local file object using a callback to handle the results. ```javascript Papa.parse(file, { complete: function(results) { console.log("Finished:", results.data); } }); ``` ```javascript Papa.parse(fileInput.files[0], { complete: function(results) { console.log(results); } }); ``` -------------------------------- ### Basic Papa Parse Usage Source: https://github.com/mholt/papaparse/blob/master/README.md Import Papa Parse and use its `parse` function to parse a file or `unparse` to convert data to CSV. Ensure the `file` and `data` variables are properly defined before use. ```javascript import Papa from 'papaparse'; Papa.parse(file, config); const csv = Papa.unparse(data[, config]); ``` -------------------------------- ### Default Parse Config Object Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html The default configuration object for the parse function, showing all available options and their default values. ```APIDOC ## Default Parse Config Object ### Description The `parse` function may be passed a configuration object. It defines settings, behavior, and callbacks used during parsing. Any properties left unspecified will resort to their default values. ### Response #### Success Response (200) - **delimiter** (string) - Auto-detect - **newline** (string) - Auto-detect - **quoteChar** (string) - `"` - **escapeChar** (string) - `"` - **header** (boolean) - `false` - **transformHeader** (function) - `undefined` - **dynamicTyping** (boolean) - `false` - **preview** (number) - `0` - **encoding** (string) - `""` - **worker** (boolean) - `false` - **comments** (boolean | string) - `false` - **step** (function) - `undefined` - **complete** (function) - `undefined` - **error** (function) - `undefined` - **download** (boolean) - `false` - **downloadRequestHeaders** (object) - `undefined` - **downloadRequestBody** (string | object) - `undefined` - **skipEmptyLines** (boolean) - `false` - **chunk** (function) - `undefined` - **chunkSize** (number) - `undefined` - **fastMode** (boolean) - `undefined` - **beforeFirstChunk** (function) - `undefined` - **withCredentials** (boolean) - `undefined` - **transform** (function) - `undefined` - **delimitersToGuess** (array) - `[',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]` - **skipFirstNLines** (number) - `0` ### Response Example ```json { delimiter: "", // auto-detect newline: "", // auto-detect quoteChar: '"', escapeChar: '"', header: false, transformHeader: undefined, dynamicTyping: false, preview: 0, encoding: "", worker: false, comments: false, step: undefined, complete: undefined, error: undefined, download: false, downloadRequestHeaders: undefined, downloadRequestBody: undefined, skipEmptyLines: false, chunk: undefined, chunkSize: undefined, fastMode: undefined, beforeFirstChunk: undefined, withCredentials: undefined, transform: undefined, delimitersToGuess: [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP], skipFirstNLines: 0 } ``` ``` -------------------------------- ### Define a step callback for streaming Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Use the step callback to process rows individually during streaming, which is essential for handling large files without crashing the browser. ```javascript step: function(results, parser) { console.log("Row data:", results.data); console.log("Row errors:", results.errors); } ``` -------------------------------- ### Unparse Config Options Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Configuration options to customize the CSV output during unparsing. ```APIDOC ## Unparse Config Options ### Description Configuration options to customize the CSV output during unparsing. ### Parameters #### Request Body - **quotes** (boolean | array | function) - Optional - If `true`, forces all fields to be enclosed in quotes. If an array of `true/false` values, specifies which fields should be force-quoted. A function can also be used to determine the quotes value of a cell. - **quoteChar** (string) - Optional - The character used to quote fields. - **escapeChar** (string) - Optional - The character used to escape `quoteChar` inside field values. - **delimiter** (string) - Optional - The delimiting character. Multi-character delimiters are supported. - **header** (boolean | array | object) - Optional - If `false`, will omit the header row. If `data` is an array of objects, the keys of the first object are the header row. If `data` is an object with keys `fields` and `data`, the `fields` are the header row. - **newline** (string) - Optional - The character used to determine newline sequence. Defaults to `"\r\n"`. - **skipEmptyLines** (boolean | string) - Optional - If `true`, lines that are completely empty will be skipped. If set to `'greedy'`, lines with only whitespace after parsing will also be skipped. - **columns** (array) - Optional - If `data` is an array of objects, this option can be used to manually specify the keys (columns) you expect in the objects. - **escapeFormulae** (boolean | regex) - Optional - If `true`, field values that begin with `=`, `+`, `-`, `@`, `\t`, or `\r`, will be prepended with a `'` to defend against injection attacks. Can be overridden by setting this option to a regular expression. ### Request Example ```javascript var csv = Papa.unparse([ ["1-1", "1-2", "1-3"], ["2-1", "2-2", "2-3"] ]); var csv = Papa.unparse([ { "Column 1": "foo", "Column 2": "bar" }, { "Column 1": "abc", "Column 2": "def" } ]); var csv = Papa.unparse({ "fields": ["Column 1", "Column 2"], "data": [ ["foo", "bar"], ["abc", "def"] ] }); ``` ``` -------------------------------- ### PapaParse Data Transformation and Delimiter Options Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Options for transforming data during parsing and specifying delimiters. ```APIDOC ### `withCredentials` - **Description**: A boolean value passed directly into XMLHttpRequest's "withCredentials" property. ### `transform` - **Description**: A function to apply on each value. The function receives the value as its first argument and the column number or header name (when enabled) as its second argument. The return value of the function will replace the original value. The transform function is applied before `dynamicTyping`. ### `delimitersToGuess` - **Description**: An array of delimiters to guess from if the `delimiter` option is not set. ### `skipFirstNLines` - **Description**: Skips the first N number of lines when converting a CSV file to JSON. ``` -------------------------------- ### Define a complete callback Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html The complete callback executes after parsing finishes. Note that results are not available in this callback when streaming. ```javascript complete: function(results, file) { console.log("Parsing complete:", results, file); } ``` -------------------------------- ### Papa.parse Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Parses delimited data from strings, local files, or remote URLs. ```APIDOC ## Papa.parse ### Description Parses delimited data from a string, a local File object, or a remote URL. ### Parameters #### Arguments - **input** (string/File/url) - Required - The source data to parse. - **config** (object) - Optional - Configuration object for parsing behavior. ### Request Example // Parse string Papa.parse(csvString, config); // Parse local file Papa.parse(file, config); // Parse remote file Papa.parse(url, { download: true }); ``` -------------------------------- ### Streaming Remote Files Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Stream a large remote file row-by-row to manage memory usage. ```javascript Papa.parse("http://example.com/big.csv", { download: true, step: function(row) { console.log("Row:", row.data); }, complete: function() { console.log("All done!"); } }); ``` -------------------------------- ### PapaParse Default Parse Configuration Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html This object represents the default configuration for the Papa.parse function. Any unspecified properties will use their default values. ```javascript { delimiter: "", // auto-detect newline: "", // auto-detect quoteChar: '"', escapeChar: '"', header: false, transformHeader: undefined, dynamicTyping: false, preview: 0, encoding: "", worker: false, comments: false, step: undefined, complete: undefined, error: undefined, download: false, downloadRequestHeaders: undefined, downloadRequestBody: undefined, skipEmptyLines: false, chunk: undefined, chunkSize: undefined, fastMode: undefined, beforeFirstChunk: undefined, withCredentials: undefined, transform: undefined, delimitersToGuess: [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP], skipFirstNLines: 0 } ``` -------------------------------- ### Parse Files with jQuery Plugin Source: https://context7.com/mholt/papaparse/llms.txt Use the jQuery plugin to easily parse files from file input elements. Configure parsing options and handle results with callbacks. ```javascript // Parse all files from file inputs $("input[type=file]").parse({ config: { header: true, dynamicTyping: true, skipEmptyLines: true }, before: function(file, inputElem) { console.log("About to parse:", file.name); // Return object to control flow // return { action: "abort", reason: "User cancelled" }; // Stop all // return { action: "skip" }; // Skip this file // return { config: { delimiter: ";" } }; // Override config for this file }, error: function(err, file, inputElem, reason) { console.error("Error parsing", file.name, ":", err); }, complete: function() { console.log("All files have been parsed!"); } }); // With per-file results callback $("#csvUpload").parse({ config: { header: true, complete: function(results, file) { // Called for each file after parsing console.log("Parsed", file.name, ":", results.data.length, "rows"); processFileData(file.name, results.data); } }, complete: function() { // Called after ALL files are done console.log("Batch processing complete"); } }); ``` -------------------------------- ### Parse Remote File Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Parses a file from a given URL. Set `download: true` in the configuration object. Results are provided asynchronously to a callback function. ```javascript Papa.parse(url, { download: true, // rest of config ... }) ``` -------------------------------- ### Parse Large Files with Worker Threads Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Use worker threads for large files to keep the page reactive. Specify `worker: true` in the configuration. ```javascript Papa.parse(bigFile, { worker: true, step: function(row) { console.log("Row:", row.data); }, complete: function() { console.log("All done!"); } }); ``` -------------------------------- ### PapaParse Read-Only Properties Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Exposes several read-only properties for utility and information. ```APIDOC ## Read-Only Properties ### `Papa.BAD_DELIMITERS` - **Description**: An array of characters that are not allowed as delimiters (`\r`, `\n`, `"`, `\ufeff`). ### `Papa.BYTE_ORDER_MARK` - **Description**: The unicode [Byte Order Mark](https://en.wikipedia.org/wiki/Byte_order_mark) (`\ufeff`). ### `Papa.RECORD_SEP` - **Description**: The true delimiter. Invisible. ASCII code 30. Should be doing the job we strangely rely upon commas and tabs for. ### `Papa.UNIT_SEP` - **Description**: Also sometimes used as a delimiting character. ASCII code 31. ### `Papa.WORKERS_SUPPORTED` - **Description**: Whether or not the browser supports HTML5 Web Workers. If `false`, `worker: true` will have no effect. ``` -------------------------------- ### Papa.parse - Parse Local File Source: https://context7.com/mholt/papaparse/llms.txt Parses a File object asynchronously, supporting streaming for large files. ```APIDOC ## Papa.parse (File) ### Description Parses a File object from a file input element asynchronously. Results are delivered via callbacks. ### Parameters #### Request Body - **file** (File) - Required - The File object to parse. - **config** (object) - Required - Configuration object including callbacks like `complete`, `error`, and `step` for streaming. ### Response #### Success Response (200) - **results** (object) - Contains parsed data, errors, and metadata. - **file** (File) - The original file object. ``` -------------------------------- ### jQuery File Parsing Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Parses files selected via jQuery input elements. ```APIDOC ## jQuery File Parsing ### Description Uses jQuery to select file inputs and parse the selected files with specific callbacks. ### Parameters #### Options - **config** (object) - Required - Base configuration for parsing. - **before** (function) - Optional - Callback executed before parsing each file. - **error** (function) - Optional - Callback executed if an error occurs. - **complete** (function) - Optional - Callback executed after all files are processed. ### Request Example $('input[type=file]').parse({ config: {}, before: function(file, inputElem) {}, error: function(err, file, inputElem, reason) {}, complete: function() {} }); ``` -------------------------------- ### Parse CSV with Header Row Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Key data by field name instead of index by setting `header: true`. ```javascript // Key data by field name instead of index/position var results = Papa.parse(csv, { header: true }); ``` -------------------------------- ### Parse Local File Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Parses a File object obtained from the DOM. Requires a configuration object with a callback function for results. Does not return a value; results are delivered asynchronously. ```javascript Papa.parse(file, config) ``` -------------------------------- ### Skip First N Lines of CSV Source: https://context7.com/mholt/papaparse/llms.txt Use the 'skipFirstNLines' option to ignore a specified number of lines at the beginning of a CSV file. This is useful for files that contain metadata or non-data headers before the actual CSV content. ```javascript // Skip first N lines (useful for files with metadata headers) Papa.parse(csvWithMetadata, { header: true, skipFirstNLines: 3, // Skip first 3 lines before parsing complete: function(results) { console.log(results.data); } }); ``` -------------------------------- ### Handle Comments in CSV Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Specify the comment string using `comments: "#"` to skip commented lines in the CSV file. ```javascript // Mostly found in academia, some CSV files // may have commented lines in them var results = Papa.parse(csv, { comments: "#" }); ``` -------------------------------- ### Basic CSV Parsing and Unparsing Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Parse a CSV string into data or convert data back into a CSV string. ```javascript // Parse CSV string var data = Papa.parse(csv); // Convert back to CSV var csv = Papa.unparse(data); ``` -------------------------------- ### Papa.parse - Parse Local File Source: https://context7.com/mholt/papaparse/llms.txt Parses a File object from a file input element. Use 'complete' for final results, 'error' for errors, and 'step' for streaming large files row-by-row. Options like 'header', 'dynamicTyping', and 'skipEmptyLines' are supported. ```javascript // HTML: document.getElementById('csvFile').addEventListener('change', function(e) { const file = e.target.files[0]; Papa.parse(file, { header: true, dynamicTyping: true, skipEmptyLines: true, complete: function(results, file) { console.log("Parsing complete!"); console.log("Rows parsed:", results.data.length); console.log("Errors:", results.errors); console.log("First row:", results.data[0]); }, error: function(error, file) { console.error("Error reading file:", error); } }); }); ``` ```javascript // Stream large files row-by-row to avoid memory issues Papa.parse(largeFile, { header: true, step: function(results, parser) { // Process one row at a time console.log("Row:", results.data); // Pause parsing if needed if (shouldPause) { parser.pause(); setTimeout(() => parser.resume(), 1000); } // Abort parsing early if needed if (shouldStop) { parser.abort(); } }, complete: function() { console.log("All rows processed"); } }); ``` -------------------------------- ### Parse Remote CSV Files Source: https://context7.com/mholt/papaparse/llms.txt Use Papa.parse with the download option to fetch and parse CSV data from a URL. Supports authentication headers, POST requests, and chunked streaming for large files. ```javascript // Basic remote file parsing Papa.parse("https://example.com/data.csv", { download: true, header: true, complete: function(results) { console.log("Downloaded and parsed:", results.data); }, error: function(error) { console.error("Download failed:", error); } }); // With authentication headers Papa.parse("https://api.example.com/export.csv", { download: true, downloadRequestHeaders: { 'Authorization': 'Bearer your-token-here', 'Accept': 'text/csv' }, header: true, complete: function(results) { console.log("Authenticated data:", results.data); } }); // POST request with body Papa.parse("https://api.example.com/generate-csv", { download: true, downloadRequestBody: JSON.stringify({ filter: "active", limit: 1000 }), header: true, complete: function(results) { console.log("Generated CSV data:", results.data); } }); // Stream remote file in chunks Papa.parse("https://example.com/large-file.csv", { download: true, header: true, chunkSize: 1024 * 1024, // 1MB chunks chunk: function(results, parser) { console.log("Chunk received:", results.data.length, "rows"); // Process chunk... }, complete: function() { console.log("Remote file fully processed"); } }); ``` -------------------------------- ### Delimiter Detection Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Automatically detect the delimiter by scanning the first few rows of the CSV. ```javascript var results = Papa.parse(csvString); console.log(results.meta.delimiter); // "\t" ``` -------------------------------- ### Papa Parse jQuery Plugin Usage Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Use Papa Parse with jQuery to parse files from input elements. Papa Parse has no dependencies. ```javascript $("input[type=file]").parse({ config: { complete: function(results, file) { console.log("This file done:", file, results); } }, complete: function() { console.log("All files done!"); } }); ``` -------------------------------- ### PapaParse Result Object Structure Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Details the structure of the object returned after parsing, including data, errors, and metadata. ```APIDOC ## The Parse Result Object A parse result always contains three objects: `data`, `errors`, and `meta`. `data` and `errors` are arrays, and `meta` is an object. In the `step` callback, the `data` array will only contain one element. ### Result Structure ```json { "data": // array of parsed data "errors": // array of errors "meta": // object with extra info } ``` ### Data - `data` is an array of rows. If `header` is `false`, rows are arrays; otherwise, they are objects keyed by the field name. - If a header row is enabled and more fields are found on a row of data than in the header row, an extra field called `__parsed_extra` will appear in that row. It contains an array of all data parsed from that row that extended beyond the header row. **Example (header: false):** ```json [ ["Column 1", "Column 2"], ["foo", "bar"], ["abc", "def"] ] ``` **Example (header: true):** ```json [ { "Column 1": "foo", "Column 2": "bar", "Column 1": "foo1" }, { "Column 1": "abc", "Column 2": "def", "Column 1": "abc1" } ] ``` ### Errors - `errors` is an array of [errors](#errors). - **Error Structure:** ```json { "type": "", // A generalization of the error "code": "", // Standardized error code "message": "", // Human-readable details "row": 0 // Row index of parsed data where error is } ``` - The error `type` will be one of "Quotes", "Delimiter", or "FieldMismatch". - The `code` may be "MissingQuotes", "UndetectableDelimiter", "TooFewFields", or "TooManyFields" (depending on the error type). - The generation of errors does not necessarily mean parsing failed. The worst error you can get is probably MissingQuotes. ### Meta - `meta` contains extra information about the parse, such as the delimiter used, the newline sequence, whether the process was aborted, etc. Properties in this object are not guaranteed to exist in all situations. - **Meta Properties:** - `delimiter`: Delimiter used. - `linebreak`: Line break sequence used. - `aborted`: Whether the process was aborted. - `fields`: Array of field names (only given when header row is enabled). - `truncated`: Whether the preview consumed all input. - `renamedHeaders`: Headers that are automatically renamed by the library to avoid duplication. Example: `{ "Column 1_1": "Column 1" }` (the later header 'Column 1' was renamed to 'Column 1_1'). ``` -------------------------------- ### Parse Result Meta Structure Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html The 'meta' object contains additional parsing information such as the delimiter used, line break sequence, and whether the process was aborted. Not all properties are guaranteed to be present. ```json { delimiter: // Delimiter used linebreak: // Line break sequence used aborted: // Whether process was aborted fields: // Array of field names truncated: // Whether preview consumed all input renamedHeaders: // Headers that are automatically renamed by the library to avoid duplication. {Column 1_1: 'Column 1' // the later header 'Column 1' was renamed to 'Column 1_1'} } ``` -------------------------------- ### Parse CSV String Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Parses a string containing delimited text. An optional configuration object can be provided. Returns a parse results object unless streaming or using a worker. ```javascript Papa.parse(csvString[, config]) ``` -------------------------------- ### Streaming Large Files with Workers Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Process large files in a worker thread to avoid blocking the main browser thread. ```javascript Papa.parse(bigFile, { worker: true, step: function(results) { console.log("Row:", results.data); } }); ``` -------------------------------- ### Papa.parse - Parse CSV String Source: https://context7.com/mholt/papaparse/llms.txt Parses a CSV-formatted string and returns a result object containing the parsed data, errors, and metadata. ```APIDOC ## Papa.parse (String) ### Description Parses a CSV-formatted string and returns a result object containing the parsed data as a JavaScript array, any errors encountered, and metadata about the parsing process. ### Parameters #### Request Body - **input** (string) - Required - The CSV-formatted string to parse. - **config** (object) - Optional - Configuration object including options like `header` (boolean) and `dynamicTyping` (boolean). ### Response #### Success Response (200) - **data** (array) - The parsed CSV data. - **errors** (array) - List of errors encountered during parsing. - **meta** (object) - Metadata including delimiter, linebreak, and fields. ``` -------------------------------- ### Papa.unparse Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Converts JSON data (array of arrays or objects) into a delimited text string. ```APIDOC ## Papa.unparse ### Description Writes out delimited text strings from an array of arrays or an array of objects. ### Parameters #### Arguments - **data** (array/object) - Required - The data to convert. - **config** (object) - Optional - Configuration for output formatting. ### Response - **result** (string) - The resulting delimited text string. ``` -------------------------------- ### Unparse with Explicit Fields and Data Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Unparses data into a CSV string by explicitly defining the header fields and the data rows. This provides more control over the output structure. ```javascript var csv = Papa.unparse({ "fields": ["Column 1", "Column 2"], "data": [ ["foo", "bar"], ["abc", "def"] ] }); ``` -------------------------------- ### Convert JSON to CSV Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Converts an array of arrays or an array of objects into a delimited text string. An optional configuration object can be provided to customize the output. ```javascript Papa.unparse(data[, config]) ``` -------------------------------- ### Unparse Data to CSV Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Converts an array of arrays into a comma-delimited CSV string. Ensure data is properly formatted before unparsing. ```javascript var csv = Papa.unparse([ ["1-1", "1-2", "1-3"], ["2-1", "2-2", "2-3"] ]); ``` -------------------------------- ### Node.js Streaming with Duplex Streams Source: https://context7.com/mholt/papaparse/llms.txt Integrate Papa Parse with Node.js stream ecosystem for processing CSV data from various sources. This enables piping CSV data through the parsing pipeline. ```javascript const Papa = require('papaparse'); const fs = require('fs'); // Create a duplex stream for parsing const parseStream = Papa.parse(Papa.NODE_STREAM_INPUT, { header: true, dynamicTyping: true }); // Pipe file through parser fs.createReadStream('data.csv') .pipe(parseStream) .on('data', (row) => { console.log('Parsed row:', row); }) .on('end', () => { console.log('Finished parsing'); }) .on('error', (err) => { console.error('Parse error:', err); }); // Parse readable stream directly const readableStream = fs.createReadStream('large-file.csv'); Papa.parse(readableStream, { header: true, step: function(results) { console.log('Row:', results.data); }, complete: function() { console.log('Stream parsing complete'); } }); ``` -------------------------------- ### Parse Result Object Structure Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html The parse result object contains 'data', 'errors', and 'meta' properties. 'data' and 'errors' are arrays, and 'meta' is an object with extra information. ```json { data: // array of parsed data errors: // array of errors meta: // object with extra info } ``` -------------------------------- ### Papa.parse - Parse CSV String Source: https://context7.com/mholt/papaparse/llms.txt Parses a CSV-formatted string. Use the 'header' option to convert rows to objects and 'dynamicTyping' to automatically convert numbers and booleans. Access parsing metadata via the 'meta' property. ```javascript // Basic string parsing const csv = "Name,Age,City\nAlice,30,New York\nBob,25,Los Angeles"; const results = Papa.parse(csv); console.log(results.data); // Output: [["Name","Age","City"],["Alice","30","New York"],["Bob","25","Los Angeles"]] ``` ```javascript // Parse with header row - converts to array of objects const resultsWithHeader = Papa.parse(csv, { header: true }); console.log(resultsWithHeader.data); // Output: [ // { Name: "Alice", Age: "30", City: "New York" }, // { Name: "Bob", Age: "25", City: "Los Angeles" } // ] ``` ```javascript // Parse with dynamic typing - automatically converts numbers and booleans const csvWithTypes = "Product,Price,InStock\nWidget,19.99,true\nGadget,49.50,false"; const typedResults = Papa.parse(csvWithTypes, { header: true, dynamicTyping: true }); console.log(typedResults.data); // Output: [ // { Product: "Widget", Price: 19.99, InStock: true }, // { Product: "Gadget", Price: 49.50, InStock: false } // ] ``` ```javascript // Access parsing metadata console.log(resultsWithHeader.meta); // Output: { delimiter: ",",linebreak: "\n", aborted: false, fields: ["Name","Age","City"], truncated: false } ``` -------------------------------- ### Transform Headers During Parsing Source: https://context7.com/mholt/papaparse/llms.txt Customize header field names during parsing using the 'transformHeader' function. This allows for consistent naming conventions, such as converting to lowercase and replacing spaces with underscores. ```javascript // Transform headers Papa.parse(csvData, { header: true, transformHeader: function(header, index) { // Convert to lowercase and replace spaces with underscores return header.toLowerCase().replace(/\s+/g, '_'); }, complete: function(results) { // Headers are now: first_name, last_name, email_address console.log(results.meta.fields); } }); ``` -------------------------------- ### PapaParse Read-Only Properties Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html PapaParse exposes several read-only properties for accessing constants related to delimiters and character encodings. ```javascript Papa.BAD_DELIMITERS Papa.BYTE_ORDER_MARK Papa.RECORD_SEP Papa.UNIT_SEP Papa.WORKERS_SUPPORTED ``` -------------------------------- ### Convert JSON to CSV Source: https://github.com/mholt/papaparse/blob/master/docs/index.html Use `Papa.unparse()` to convert an array of arrays or array of objects into a CSV string. ```javascript // Output is a properly-formatted CSV string. // See the docs for more configurability. var csv = Papa.unparse(yourData); ``` -------------------------------- ### Unparse Array of Objects with Implicit Header Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html Unparses an array of objects into a CSV string, using the object keys as the header row. This is useful when your data is already structured as objects. ```javascript var csv = Papa.unparse([ { "Column 1": "foo", "Column 2": "bar" }, { "Column 1": "abc", "Column 2": "def" } ]); ``` -------------------------------- ### Handle CSV Parsing Errors and Validation Source: https://context7.com/mholt/papaparse/llms.txt Access error details through the results object and validate field counts using error codes. ```javascript const malformedCsv = 'Name,Age\n"Alice,30\nBob,25'; const results = Papa.parse(malformedCsv, { header: true }); // Check for errors if (results.errors.length > 0) { results.errors.forEach(function(error) { console.log("Error type:", error.type); // "Quotes", "Delimiter", or "FieldMismatch" console.log("Error code:", error.code); // "MissingQuotes", "TooFewFields", etc. console.log("Message:", error.message); // Human-readable description console.log("Row:", error.row); // Row index where error occurred }); } // Data is still returned even with errors console.log("Parsed data:", results.data); // Validate field counts const csvWithMismatch = "A,B,C\n1,2\n3,4,5,6"; const validated = Papa.parse(csvWithMismatch, { header: true }); validated.errors.forEach(function(e) { if (e.code === 'TooFewFields') { console.log("Row", e.row, "has too few fields"); } if (e.code === 'TooManyFields') { console.log("Row", e.row, "has too many fields"); } }); ``` -------------------------------- ### Parse Result Error Structure Source: https://github.com/mholt/papaparse/blob/master/docs/docs.html The 'errors' property is an array of error objects, each containing a type, code, message, and the row number where the error occurred. ```json { type: "", // A generalization of the error code: "", // Standardized error code message: "", // Human-readable details row: 0, // Row index of parsed data where error is } ``` -------------------------------- ### Transform Values During Parsing Source: https://context7.com/mholt/papaparse/llms.txt Modify cell values during parsing using the 'transform' function. This is useful for cleaning or standardizing data, like trimming whitespace or converting to lowercase. ```javascript // Transform values during parsing Papa.parse(csvData, { header: true, transform: function(value, field) { // Trim whitespace from all values value = value.trim(); // Custom transformation per column if (field === 'email') { return value.toLowerCase(); } if (field === 'phone') { return value.replace(/[^0-9]/g, ''); // Remove non-digits } return value; }, complete: function(results) { console.log(results.data); } }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.