Documentation

Convert CSV to JSON

Delimited data can be parsed out of strings or files. Files that are parsed can be local. Local files are used with CSVReader component.

Parse string
readString(csvString[, config])
Source code
  • csvString is a string of delimited text to be parsed.
  • config is an config object.
  • Returns a parse results object in complete of config object (if not streaming or using worker).
Parse local files

Basic Upload

<CSVReader
  onUploadAccepted={(results: any) => {
    console.log('---------------------------');
    console.log(results);
    console.log('---------------------------');
  }}
>
  {({
    getRootProps,
    acceptedFile,
    ProgressBar,
    getRemoveFileProps,
  }: any) => (
    <>
      <div style={styles.csvReader}>
        <button type='button' {...getRootProps()} style={styles.browseFile}>
          Browse file
        </button>
        <div style={styles.acceptedFile}>
          {acceptedFile && acceptedFile.name}
        </div>
        <button {...getRemoveFileProps()} style={styles.remove}>
          Remove
        </button>
      </div>
      <ProgressBar style={styles.progressBarBackgroundColor} />
    </>
  )}
</CSVReader>
Source code
  • acceptis a property to be used to set MIME type for CSV. Default is 'text/csv, .csv, application/vnd.ms-excel'.
  • onUploadAccepted is the function to be called passing uploaded results.
  • noClick If true, disables click to open the native file selection dialog.
  • config is a config object which contains a callback.

Click and Drag Upload

<CSVReader
  onUploadAccepted={(results: any) => {
    console.log('---------------------------');
    console.log(results);
    console.log('---------------------------');
    setZoneHover(false);
  }}
  onDragOver={(event: DragEvent) => {
    event.preventDefault();
    setZoneHover(true);
  }}
  onDragLeave={(event: DragEvent) => {
    event.preventDefault();
    setZoneHover(false);
  }}
>
  {({
    getRootProps,
    acceptedFile,
    ProgressBar,
    getRemoveFileProps,
    Remove,
  }: any) => (
    <>
      <div
        {...getRootProps()}
        style={Object.assign(
          {},
          styles.zone,
          zoneHover && styles.zoneHover
        )}
      >
        {acceptedFile ? (
          <>
            <div style={styles.file}>
              <div style={styles.info}>
                <span style={styles.size}>
                  {formatFileSize(acceptedFile.size)}
                </span>
                <span style={styles.name}>{acceptedFile.name}</span>
              </div>
              <div style={styles.progressBar}>
                <ProgressBar />
              </div>
              <div
                {...getRemoveFileProps()}
                style={styles.remove}
                onMouseOver={(event: Event) => {
                  event.preventDefault();
                  setRemoveHoverColor(REMOVE_HOVER_COLOR_LIGHT);
                }}
                onMouseOut={(event: Event) => {
                  event.preventDefault();
                  setRemoveHoverColor(DEFAULT_REMOVE_HOVER_COLOR);
                }}
              >
                <Remove color={removeHoverColor} />
              </div>
            </div>
          </>
        ) : (
          'Drop CSV file here or click to upload'
        )}
      </div>
    </>
  )}
</CSVReader>
Source code
  • acceptis a property to be used to set MIME type for CSV. Default is 'text/csv, .csv, application/vnd.ms-excel'.
  • onUploadAccepted is the function to be called passing uploaded results.
  • config is a config object which contains a callback.

Drag ( No Click ) Upload

<CSVReader
  onUploadAccepted={(results: any) => {
    console.log('---------------------------');
    console.log(results);
    console.log('---------------------------');
    setZoneHover(false);
  }}
  onDragOver={(event: DragEvent) => {
    event.preventDefault();
    setZoneHover(true);
  }}
  onDragLeave={(event: DragEvent) => {
    event.preventDefault();
    setZoneHover(false);
  }}
  noClick
>
  {({
    getRootProps,
    acceptedFile,
    ProgressBar,
    getRemoveFileProps,
    Remove,
  }: any) => (
    <>
      <div
        {...getRootProps()}
        style={Object.assign(
          {},
          styles.zone,
          zoneHover && styles.zoneHover
        )}
      >
        {acceptedFile ? (
          <>
            <div style={styles.file}>
              <div style={styles.info}>
                <span style={styles.size}>
                  {formatFileSize(acceptedFile.size)}
                </span>
                <span style={styles.name}>{acceptedFile.name}</span>
              </div>
              <div style={styles.progressBar}>
                <ProgressBar />
              </div>
              <div
                {...getRemoveFileProps()}
                style={styles.remove}
                onMouseOver={(event: Event) => {
                  event.preventDefault();
                  setRemoveHoverColor(REMOVE_HOVER_COLOR_LIGHT);
                }}
                onMouseOut={(event: Event) => {
                  event.preventDefault();
                  setRemoveHoverColor(DEFAULT_REMOVE_HOVER_COLOR);
                }}
              >
                <Remove color={removeHoverColor} />
              </div>
            </div>
          </>
        ) : (
          'Drop CSV file here to upload'
        )}
      </div>
    </>
  )}
</CSVReader>
Source code
  • acceptis a property to be used to set MIME type for CSV. Default is 'text/csv, .csv, application/vnd.ms-excel'.
  • onUploadAccepted is the function to be called passing uploaded results.
  • noClick If true, disables click to open the native file selection dialog.
  • config is a config object which contains a callback.

Click ( No Drag ) Upload

<CSVReader
  onUploadAccepted={(results: any) => {
    console.log('---------------------------');
    console.log(results);
    console.log('---------------------------');
    setZoneHover(false);
  }}
  onDragOver={(event: DragEvent) => {
    event.preventDefault();
    setZoneHover(true);
  }}
  onDragLeave={(event: DragEvent) => {
    event.preventDefault();
    setZoneHover(false);
  }}
  noDrag
>
  {({
    getRootProps,
    acceptedFile,
    ProgressBar,
    getRemoveFileProps,
    Remove,
  }: any) => (
    <>
      <div
        {...getRootProps()}
        style={Object.assign(
          {},
          styles.zone,
          zoneHover && styles.zoneHover
        )}
      >
        {acceptedFile ? (
          <>
            <div style={styles.file}>
              <div style={styles.info}>
                <span style={styles.size}>
                  {formatFileSize(acceptedFile.size)}
                </span>
                <span style={styles.name}>{acceptedFile.name}</span>
              </div>
              <div style={styles.progressBar}>
                <ProgressBar />
              </div>
              <div
                {...getRemoveFileProps()}
                style={styles.remove}
                onMouseOver={(event: Event) => {
                  event.preventDefault();
                  setRemoveHoverColor(REMOVE_HOVER_COLOR_LIGHT);
                }}
                onMouseOut={(event: Event) => {
                  event.preventDefault();
                  setRemoveHoverColor(DEFAULT_REMOVE_HOVER_COLOR);
                }}
              >
                <Remove color={removeHoverColor} />
              </div>
            </div>
          </>
        ) : (
          'Click to upload'
        )}
      </div>
    </>
  )}
</CSVReader>
Source code
  • acceptis a property to be used to set MIME type for CSV. Default is 'text/csv, .csv, application/vnd.ms-excel'.
  • onUploadAccepted is the function to be called passing uploaded results.
  • noDrag If true, disables drag 'n' drop.
  • config is a config object which contains a callback.
Parse remote file
readRemoteFile(url, {
  // rest of config ...
})
Source code
  • url is the path or URL to the file to download.
  • The second argument is a config object.
  • Doesn't return anything. Results are provided asynchronously to a callback function.

Convert JSON to CSV

react-papaparse unparse utility writes out correct delimited text strings given an array of arrays or an array of objects using jsonToCSV() function.

jsonToCSV(jsonData[, config])
Source code
  • Returns the resulting delimited text as a string.
  • data can be one of:
    • An array of arrays
    • An array of objects
    • An object explicitly defining fields and data
  • config is an optional config object
Default Unparse Config with all options

{
  quotes: false, //or array of booleans
  quoteChar: '"',
  escapeChar: '"',
  delimiter: ",",
  header: true,
  newline: "\r\n",
  skipEmptyLines: false, //or 'greedy',
  columns: null //or array of strings
}
Unparse Config
OptionExplanation
quotesIf true, forces all fields to be enclosed in quotes. If an array of true/false values, specifies which fields should be force-quoted (first boolean is for the first column, second boolean for the second column, ...). A function that returns a boolean values can be used to determine the quotes value of a cell. This function accepts the cell value and column index as parameters.
quoteCharThe character used to quote fields.
escapeCharThe character used to escape quoteChar inside field values.
delimiterThe delimiting character. It must not be found in BAD_DELIMITERS.
headerIf false, will omit the header row. If data is an array of arrays this option is ignored. If data is an array of objects the keys of the first object are the header row. If data is an object with the keys fields and data the fields are the header row.
newlineThe character used to determine newline sequence. It defaults to "\r\n".
skipEmptyLinesIf true, lines that are completely empty (those which evaluate to an empty string) will be skipped. If set to 'greedy', lines that don't have any content (those which have only whitespace after parsing) will also be skipped.
columnsIf data is an array of objects this option can be used to manually specify the keys (columns) you expect in the objects. If not set the keys of the first objects are used as column.
Examples
// Two-line, comma-delimited file
const csv = jsonToCSV([
  ["1-1", "1-2", "1-3"],
  ["2-1", "2-2", "2-3"]
])
// With implicit header row
// (keys of first object populate header row)
const csv = jsonToCSV([
  {
    "Column 1": "foo",
    "Column 2": "bar"
  },
  {
    "Column 1": "abc",
    "Column 2": "def"
  }
])
// Specifying fields and data explicitly
const csv = jsonToCSV({
  "fields": ["Column 1", "Column 2"],
  "data": [
    ["foo", "bar"],
    ["abc", "def"]
  ]
})

The Parse Config Object

The readString function and CSVReader component 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.

Warning

Setting the complete callback function on the config object will disable the onDrop and/or onFileLoad functions you pass to the CSVReader component.

Setting the step callback function on the config object will disable the onDrop and/or onFileLoad functions you pass to the CSVReader component and will disable the progress bar.

Default Config With All Options
{
  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,
  skipEmptyLines: false,
  chunk: undefined,
  fastMode: undefined,
  beforeFirstChunk: undefined,
  withCredentials: undefined,
  transform: undefined,
  delimitersToGuess: [',', '	', '|', ';', RECORD_SEP, UNIT_SEP]
}
Config
OptionExplanation
delimiterThe delimiting character. Leave blank to auto-detect from a list of most common delimiters, or any values passed in through delimitersToGuess. It can be a string or a function. If string, it must be one of length 1. If a function, it must accept the input as first parameter and it must return a string which will be used as delimiter. In both cases it cannot be found in BAD_DELIMITERS.
newlineThe newline sequence. Leave blank to auto-detect. Must be one of \r, \n, or \r\n.
quoteCharThe character used to quote fields. The quoting of all fields is not mandatory. Any field which is not quoted will correctly read.
escapeCharThe character used to escape the quote character within a field. If not set, this option will default to the value of quoteChar, meaning that the default escaping of quote character within a quoted field is using the quote character two times. (e.g. "column with ""quotes"" in text")
headerIf true, the first row of parsed data will be interpreted as field names. An array of field names will be returned in meta, and each row of data will be an object of values keyed by field name instead of a simple array. Rows with a different number of fields from the header row will produce an error. Warning: Duplicate field names will overwrite values in previous fields having the same name.
transformHeaderA function to apply on each header. Requires header to be true. The function receives the header as its first argument.
dynamicTypingIf true, numeric and boolean data will be converted to their type instead of remaining strings. Numeric data must conform to the definition of a decimal literal. Numerical values greater than 2^53 or less than -2^53 will not be converted to numbers to preserve precision. European-formatted numbers must have commas and dots swapped. If also accepts an object or a function. If object it's values should be a boolean to indicate if dynamic typing should be applied for each column number (or header name if using headers). If it's a function, it should return a boolean value for each field number (or name if using headers) which will be passed as first argument.
previewIf > 0, only that many rows will be parsed.
encodingThe encoding to use when opening local files. If specified, it must be a value supported by the FileReader API.
workerWhether or not to use a worker thread. Using a worker will keep your page reactive, but may be slightly slower.
commentsA string that indicates a comment (for example, "#" or "//"). When react-papaparse encounters a line starting with this string, it will skip the line.
stepTo stream the input, define a callback function:
step: (results, parser) => {
  console.log("Row data:", results.data)
  console.log("Row errors:", results.errors)
}
Streaming is necessary for large files which would otherwise crash the browser. You can call parser.abort() to abort parsing. And, except when using a Web Worker, you can call parser.pause() to pause it, and parser.resume() to resume.
completeThe callback to execute when parsing is complete. It receives the parse results. If parsing a local file, the File is passed in, too:
complete: (results, file) => {
  console.log("Parsing complete:", results, file)
}
When streaming, parse results are not available in this callback.
errorA callback to execute if FileReader encounters an error. The function is passed two arguments: the error and the File.
downloadRequestHeadersIf defined, should be an object that describes the headers, example:
downloadRequestHeaders: {
  'Authorization': 'token 123345678901234567890',
}
skipEmptyLinesIf true, lines that are completely empty (those which evaluate to an empty string) will be skipped. If set to 'greedy', lines that don't have any content (those which have only whitespace after parsing) will also be skipped.
chunkA callback function, identical to step, which activates streaming. However, this function is executed after every chunk of the file is loaded and parsed rather than every row. Works only with local and remote files. Do not use both chunk and step callbacks together. For the function signature, see the documentation for the step function.
fastModeFast mode speeds up parsing significantly for large inputs. However, it only works when the input has no quoted fields. Fast mode will automatically be enabled if no " characters appear in the input. You can force fast mode either way by setting it to true or false.
beforeFirstChunkA function to execute before parsing the first chunk. Can be used with chunk or step streaming modes. The function receives as an argument the chunk about to be parsed, and it may return a modified chunk to parse. This is useful for stripping header lines (as long as the header fits in a single chunk).
withCredentialsA boolean value passed directly into XMLHttpRequest's "withCredentials" property.
transformA 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 value it received. The transform function is applied before dynamicTyping.
delimitersToGuessAn array of delimiters to guess from if the delimiter option is not set.

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
{
  data:   // array of parsed data
  errors: // array of errors
  meta:   // object with extra info
}
  • data is an array of rows. If header is false, rows are arrays; otherwise they are objects of data keyed by the field name.
  • errors is an array of errors.
  • meta contains extra information about the parse, such as delimiter used, the newline sequence, whether the process was aborted, etc. Properties in this object are not guaranteed to exist in all situations.
Data
// Example (header: false)
[
  ["Column 1", "Column 2"],
  ["foo", "bar"],
  ["abc", "def"]
]

// Example (header: true)
[
  {
    "Column 1": "foo",
    "Column 2": "bar"
  },
  {
    "Column 1": "abc",
    "Column 2": "def"
  }
]
  • If header row is enabled and more fields are found on a row of data than in the header row, an extra field will appear in that row called __parsed_extra. It contains an array of all data parsed from that row that extended beyond the header row.
Errors
// Error structure
{
  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).
  • Just because errors are generated does not necessarily mean that parsing failed. The worst error you can get is probably MissingQuotes.
Meta
{
  delimiter: // Delimiter used
  linebreak: // Line break sequence used
  aborted:   // Whether process was aborted
  fields:    // Array of field names
  truncated: // Whether preview consumed all input
}
  • Not all meta properties will always be available. For instance, fields is only given when header row is enabled.

Extras

There's a few other things that react-papaparse exposes to you that weren't explained above.

Read-Only
Read-Only PropertyExplanation
BAD_DELIMITERSAn array of characters that are not allowed as delimiters.
RECORD_SEPThe true delimiter. Invisible. ASCII code 30. Should be doing the job we strangely rely upon commas and tabs for.
UNIT_SEPAlso sometimes used as a delimiting character. ASCII code 31.
WORKERS_SUPPORTEDWhether or not the browser supports HTML5 Web Workers. If false, worker: true will have no effect.
Configurable
Configurable PropertyExplanation
LocalChunkSizeThe size in bytes of each file chunk. Used when streaming files obtained from the DOM that exist on the local computer. Default 10 MB.
DefaultDelimiterThe delimiter used when it is left unspecified and cannot be detected automatically. Default is comma.

CSVDownloader

Allow to download CSV file from js object.

<CSVDownloader
  type={Type.Button}
  filename={'filename'}
  bom={true}
  config={
    {
      delimiter: ';',
    }
  }
  data={[
    {
      "Column 1": "1-1",
      "Column 2": "1-2",
      "Column 3": "1-3",
      "Column 4": "1-4",
    },
  ]}
>
  Download
</CSVDownloader>
Source code
  • bom is used to indicate Unicode encoding of a text file. If true, indicate Unicode encoding of a text file.
  • type If "button", render button.
  • config is a config object which contains a callback.

data= can be a function that returns a data object.

<CSVDownloader
  filename={'filename'}
  data={() => {
    return [
      {
        "Column 1": "1-1",
        "Column 2": "1-2",
        "Column 3": "1-3",
        "Column 4": "1-4",
      }
    ]}
  }
>
  Download
</CSVDownloader>