json-2-csv

repository·main·Indexed 19 days ago

https://github.com/mrodrig/json-2-csv

A Node.js module and CLI for bidirectional conversion between JSON arrays and CSV strings. Version 5.5.11 supports automatic header generation, nested JSON structures using dot notation, and RFC 4180 compliance. It provides the json2csv() and csv2json() functions, as well as a separate CLI package (@mrodrig/json-2-csv-cli) for terminal-based conversions.

Tokens
6.2K
Snippets
16
Records
31
Agent score
54%

What's inside json-2-csv

  1. Overview of json-2-csv functionality

    main

    The json-2-csv module provides bidirectional conversion between JSON arrays and CSV strings:

    • JSON to CSV: Converts an array of JSON documents into a CSV string. Column headings are automatically generated from JSON keys. For nested documents, keys are joined using a . separator (e.g., user.name).
    • CSV to JSON: Converts a CSV string back into an array of JSON documents. The CSV column headings are used as the keys for the resulting JSON objects. Note that all CSV lines must contain the exact same number of values for successful conversion.
  2. Key features of json-2-csv

    main

    The json-2-csv library provides several advanced data transformation capabilities:

    • Header Generation: Automatically generates headers based on document keys.
    • Key Selection: Use the options.keys parameter to convert specific keys in both json2csv and csv2json.
    • Schema Verification: Supports document schema verification (field order is ignored).
    • Complex Data Support: Natively supports sub-documents and arrays as document values.
    • Customization: Allows for custom column ordering, custom field delimiters, and end-of-line delimiters.
    • JSON Reconstruction: Ability to re-generate the original JSON documents from a CSV (including nested documents).
    • RFC 4180 Compliance: Fully compliant with RFC 4180 standards.
    • Wrapped Values: Support for wrapped values in both json2csv and csv2json.
    • Multiple Schemas: Support for multiple different schemas.
    • Empty Fields: Option to handle empty field values.
    • TypeScript Support: Includes built-in TypeScript typings.
    • Synchronous Support: Supports synchronous use cases.
  3. Migrate from v4 to v5: Synchronous API availability

    main

    In version 5, json-2-csv has transitioned its internal flow to be entirely synchronous. This change allows you to perform conversions synchronously, which is useful for environments where asynchronous code is not feasible or where immediate conversion is required.

    While the methods are now synchronous, they still return Promises if used in an asynchronous context, allowing you to continue using async/await patterns for asynchronous use cases.

    const converter = require('json-2-csv');
    
    // Synchronous usage:
    const csv = converter.json2csv([ { level: 'info', message: 'Our first test' }]);
    console.log('First output is', csv);
    
    // Asynchronous usage (still supported):
    async function runConversion() {
        return converter.json2csv([ { level: 'info', message: 'Another test...' }]);
    }
    
    async function runAsync() {
        const csv = await runConversion();
        console.log('Second output is', csv);
    }
    
    runAsync();
  4. Migrate from v3 to v4: Replace callbacks with Promises

    main
    In version 4 and later, json-2-csv has dropped support for the callback-based flow in favor of a Promise-based API. If your code relies on passing a callback function to json2csv or csv2json, you must refactor your code to use .then() or await with the new Promise-based function names.
  5. Migrate from v3 to v4: Update function names

    main

    When upgrading from version 3 to version 4, the function names for the Promise-based API have been simplified because the callback-based versions were removed. Update your imports and calls as follows:

    Old Function Name (v3)New Function Name (v4+)
    json2csvAsyncjson2csv
    json2csvPromisifiedjson2csv
    json2csv (using callback)Dropped
    csv2jsonAsynccsv2json
    csv2jsonPromisifiedcsv2json
    csv2json (using callback)Dropped
    // v3 (Callback style - DEPRECATED/REMOVED)
    // json2csv(data, opts, (err, csv) => { ... });
    
    // v4+ (Promise style)
    // Using async/await
    const csv = await json2csv(data, opts);
    
    // Or using .then()
    json2csv(data, opts).then(csv => { ... });
  6. Handle nested objects and arrays in JSON

    main

    The library provides mechanisms to flatten complex JSON structures into a flat CSV format:

    Flattening Nested Objects

    By default, the library uses deeks to extract deep keys. Nested paths are represented using dot notation (e.g., user.name.first). You can control how these are displayed using fieldTitleMap or by providing specific keys in the options.

    Unwinding Arrays

    If your JSON contains arrays, you can transform them into multiple CSV rows using the unwindArrays option. If expandArrayObjects is also set to true, the library will attempt to expand array objects into separate rows until no more nested arrays remain.

    Wildcard Key Matching

    When providing a list of keys in the options, you can use an object with wildcardMatch: true to include all keys that match a specific prefix.

    // Example of selecting specific keys with custom titles
    const json2csv = Json2Csv({
      keys: [
        { field: 'user.id', title: 'ID' },
        { field: 'user.name.first', title: 'First Name' },
        { field: 'metadata.*', wildcardMatch: true }
      ]
    });