mrodrig / json-2-csv

Convert JSON to CSV *or* CSV to JSON!

Home Page:https://mrodrig.github.io/json-2-csv

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

json-2-csv

Convert JSON to CSV or CSV to JSON

NPM version Typings Downloads Minzipped Size

Build Status Coverage Status Maintainability

This node module will convert an array of JSON documents to a CSV string. Column headings will be automatically generated based on the keys of the JSON documents. Nested documents will have a '.' appended between the keys.

It is also capable of converting CSV of the same form back into the original array of JSON documents. The columns headings will be used as the JSON document keys. All lines must have the same exact number of CSV values.

Installation

$ npm install json-2-csv

CLI:

$ npm install @mrodrig/json-2-csv-cli

Upgrading?

Upgrading to v5 from v4? Check out the upgrade guide.

Usage

let converter = require('json-2-csv');
const csv = await converter.json2csv(data, options);

or

import { json2csv } from 'json-2-csv';

API

json2csv(array, options) => string

Returns the CSV string or rejects with an Error if there was an issue.

  • array - An array of JSON documents to be converted to CSV.
  • options - (Optional) A JSON document specifying any of the following key value pairs:
    • arrayIndexesAsKeys - Boolean - Should array indexes be included in the generated keys?
      • Default: false
      • Note: This provides a more accurate representation of the JSON in the returned CSV, but may be less human readable. See #207 for more details.
    • checkSchemaDifferences - Boolean - Should all documents have the same schema?
      • Default: false
      • Note: An error will be thrown if some documents have differing schemas when this is set to true.
    • delimiter - Document - Specifies the different types of delimiters
      • field - String - Field Delimiter.
        • Default: ,
      • wrap - String - Wrap values in the delimiter of choice (e.g. wrap values in quotes).
        • Default: "
      • eol - String - End of Line Delimiter.
        • Default: \n
    • emptyFieldValue - Any - Value that, if specified, will be substituted in for field values that are undefined, null, or an empty string.
      • Default: none
    • escapeHeaderNestedDots - Boolean - Should nested dots in header keys be escaped?
      • Default: true
      • Example:
      [
        {
          "a.a": "1"
        }
      ]
      • true will generate the following CSV:
      a\.a
      1
      
      • false will generate the following CSV:
      a.a
      1
      
      • Note: This may result in CSV output that does not map back exactly to the original JSON.
    • excelBOM - Boolean - Should a unicode character be prepended to allow Excel to open a UTF-8 encoded file with non-ASCII characters present.
    • excludeKeys - Array - Specify the string keys or RegExp patterns that should be excluded from the output. Provided string keys will also be used as a RegExp to help exclude keys under a specified prefix, such as all keys of Objects in an Array when expandArrayObjects is true (e.g., providing 'baz' will exclude 'baz.a' too).
      • Default: []
      • Note: When used with unwindArrays, arrays present at excluded key paths will not be unwound.
    • expandNestedObjects - Boolean - Should nested objects be deep-converted to CSV?
      • Default: true
      • Example:
      [
      	{
        "make": "Nissan",
        "model": "Murano",
        "year": 2013,
        "specifications": {
          "mileage": 7106,
          "trim": "S AWD"
        }
      }
      ]
      • true uses the following keys:
        • ['make', 'model', 'year', 'specifications.mileage', 'specifications.trim']
      • false uses the following keys:
        • ['make', 'model', 'year', 'specifications']
      • Note: This may result in CSV output that does not map back exactly to the original JSON.
    • expandArrayObjects - Boolean - Should objects in array values be deep-converted to CSV?
      • Default: false
      • Example:
      [
      	{ 
      		"specifications": [
      			{ "features": [...] },
      			{ "mileage": "5000" }
      		]
      	}
      ]
      • true uses the following keys:
        • ['specifications.features', 'specifications.mileage']
      • false uses the following keys:
        • ['specifications']
      • Note: This may result in CSV output that does not map back exactly to the original JSON. See #102 for more information.
    • keys - Array - Specify the keys that should be converted.
      • Default: These will be auto-detected from your data by default.
      • Keys can either be specified as a String representing the key path that should be converted, or as an Object of the following format:
      {
        "field": "string", // required
        "title": "string", // optional
        "wildcardMatch": false, // optional - default: false
      }
      • When specifying keys as an Object, the field property specifies the key path, while title specifies a more human readable field heading. Additionally, the wildcardMatch option allows you to optionally specify that all auto-detected fields with the specified field prefix should be included in the CSV. The list specified can contain a combination of Objects and Strings.
      • Examples:
        • [ 'key1', 'key2', ... ]
        • [ 'key1', { field: 'key2', wildcardMatch: true }]
        • [ { field: 'key1', title: 'Key 1' }, { field: 'key2' }, 'key3', ... ]
      • Key Paths - If you are converting a nested object (ie. {info : {name: 'Mike'}}), then set this to ['info.name']
    • parseValue - Function - Specify how values should be converted into CSV format. This function is provided a single field value at a time and must return a String. The built-in parsing method is provided as the second argument for cases where default parsing is preferred.
      • Default: A built-in method is used to parse out a variety of different value types to well-known formats.
      • Note: Using this option may override other options, including useDateIso8601Format and useLocaleFormat.
    • prependHeader - Boolean - Should the auto-generated header be prepended as the first line in the CSV?
      • Default: true
    • sortHeader - Boolean or Function - Should the header keys be sorted in alphabetical order? or pass a function to use a custom sorting function
      • Default: false
    • trimFieldValues - Boolean - Should the field values be trimmed?
      • Default: false
    • trimHeaderFields - Boolean - Should the header fields be trimmed?
      • Default: false
    • unwindArrays - Boolean - Should array values be "unwound" such that there is one line per value in the array?
      • Default: false
      • Example:
      [
          {
              "_id": {"$oid": "5cf7ca3616c91100018844af"},
              "data": {"category": "Computers", "options": [{"name": "MacBook Pro 15"}, {"name": "MacBook Air 13"}]}
          },
          {
              "_id": {"$oid": "5cf7ca3616c91100018844bf"},
              "data": {"category": "Cars", "options": [{"name": "Supercharger"}, {"name": "Turbocharger"}]}
          }
      ]
      • true will unwind the JSON to four objects, and therefore four lines of CSV values:
      _id.$oid,data.category,data.options.name
      5cf7ca3616c91100018844af,Computers,MacBook Pro 15
      5cf7ca3616c91100018844af,Computers,MacBook Air 13
      5cf7ca3616c91100018844bf,Cars,Supercharger
      5cf7ca3616c91100018844bf,Cars,Turbocharger
      
      • false will leave the values unwound and will convert the array as-is (when this option is used without expandArrayObjects):
      _id.$oid,data.category,data.options
      5cf7ca3616c91100018844af,Computers,"[{""name"":""MacBook Pro 15""},{""name"":""MacBook Air 13""}]"
      5cf7ca3616c91100018844bf,Cars,"[{""name"":""Supercharger""},{""name"":""Turbocharger""}]"
      
      • Note: This may result in CSV output that does not map back exactly to the original JSON.
    • useDateIso8601Format - Boolean - Should date values be converted to an ISO8601 date string?
      • Default: false
      • Note: If selected, values will be converted using toISOString() rather than toString() or toLocaleString() depending on the other options provided.
    • useLocaleFormat - Boolean - Should values be converted to a locale specific string?
      • Default: false
      • Note: If selected, values will be converted using toLocaleString() rather than toString()
    • wrapBooleans - Boolean - Should boolean values be wrapped in wrap delimiters to prevent Excel from converting them to Excel's TRUE/FALSE Boolean values.
      • Default: false
    • preventCsvInjection - Boolean - Should CSV injection be prevented by left trimming these characters: Equals (=), Plus (+), Minus (-), At (@), Tab (0x09), Carriage return (0x0D).
      • Default: false

csv2json(csv, options) => object[]

Returns the JSON object array (object[]) or rejects with an Error if there was an issue.

  • csv - A string of CSV
  • options - (Optional) A JSON document specifying any of the following key value pairs:
    • delimiter - Document - Specifies the different types of delimiters
      • field - String - Field Delimiter.
        • Default: ,
      • wrap - String - The character that field values are wrapped in.
        • Default: "
      • eol - String - End of Line Delimiter.
        • Default: \n
    • excelBOM - Boolean - Does the CSV contain a unicode character prepended in order to allow Excel to open a UTF-8 encoded file with non-ASCII characters present?
      • Default: false
    • headerFields - Array - Specify the field names (as strings) in place of a header line in the CSV itself.
      • Default: Parses the header fields directly from the CSV string
      • If you want to generate a nested object (ie. {info : {name: 'Mike'}}), then use . characters in the string to denote a nested field, like ['info.name']
      • If your CSV has a header line included, then don't specify the option to utilize the default values that will be parsed from the CSV.
    • keys - Array - Specify the keys (as strings) that should be converted.
      • Default: null
      • If you have a nested object (ie. {info : {name: 'Mike'}}), then set this to ['info.name']
      • If you want all keys to be converted, then specify null or don't specify the option to utilize the default.
    • parseValue - Function - Specify how String representations of field values should be parsed when converting back to JSON. This function is provided a single String and can return any value.
      • Default: JSON.parse - An attempt is made to convert the String back to its original value using JSON.parse.
    • trimHeaderFields - Boolean - Should the header fields be trimmed?
      • Default: false
    • trimFieldValues - Boolean - Should the field values be trimmed?
      • Default: false

CLI

Note: As of 3.5.8, the command line interface functionality has been pulled out to a separate package. Please be sure to install the @mrodrig/json-2-csv-cli NPM package if you wish to use the CLI functionality shown below:

$ npm install @mrodrig/json-2-csv-cli

json2csv

Usage: json2csv <jsonFile> [options]

Options:
  -V, --version                    output the version number
  -o, --output [output]            Path of output file. If not provided, then stdout will be used
  -f, --field <delimiter>          Optional field delimiter
  -w, --wrap <delimiter>           Optional wrap delimiter
  -e, --eol <delimiter>            Optional end of line delimiter
  -b, --excel-bom                  Excel Byte Order Mark character prepended to CSV
  -W, --without-header             Withhold the prepended header
  -s, --sort-header                Sort the header fields
  -H, --trim-header                Trim header fields
  -F, --trim-fields                Trim field values
  -S, --check-schema               Check for schema differences
  -E, --empty-field-value <value>  Empty field value
  -A, --expand-array-objects       Expand array objects
  -k, --keys [keys]                Keys of documents to convert to CSV
  -h, --help                       output usage information

csv2json

Usage: csv2json <csvFile> [options]

Options:
  -V, --version            output the version number
  -c, --csv <csv>          Path of json file to be converted
  -o, --output [output]    Path of output file. If not provided, then stdout will be used
  -f, --field <delimiter>  Optional field delimiter
  -w, --wrap <delimiter>   Optional wrap delimiter
  -e, --eol <delimiter>    Optional end of line delimiter
  -b, --excel-bom          Excel Byte Order Mark character prepended to CSV
  -H, --trim-header        Trim header fields
  -F, --trim-fields        Trim field values
  -k, --keys [keys]        Keys of documents to convert to CSV
  -h, --help               output usage information

Tests

$ npm test

To see test coverage, please run:

$ npm run coverage

Features

  • Header Generation (per document keys)
  • Allows for conversion of specific keys in both json2csv and csv2json via the options.keys parameter (as of 1.1.2)
  • Document schema verification functionality (field order is irrelevant) (as of 1.1.0)
  • Supports sub-documents natively
  • Supports arrays as document values for both json2csv and csv2json
  • Custom ordering of columns (see F.A.Q. for more information)
  • Ability to re-generate the JSON documents that were used to generate the CSV (including nested documents)
  • Allows for custom field delimiters, end of line delimiters, etc.
  • Wrapped value support for json2csv and csv2json (as of 1.3.0)
  • Support for multiple different schemas (as of 1.4.0)
  • RFC 4180 Compliance (as of 3.0.0)
  • CLI functionality (as of 3.0.0)
    • csv2json test.csv -o output.json
    • and
    • json2csv test.json -o output.csv -W -k arrayOfStrings -o output.csv
  • Empty field value option (as of 3.1.0)
  • TypeScript typings included (as of 3.4.0) - thanks to @GabrielCastro!
  • Synchronous use case support (as of 5.0.0) - thanks to @Nokel81

About

Convert JSON to CSV *or* CSV to JSON!

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

License:MIT License


Languages

Language:TypeScript 98.3%Language:JavaScript 1.7%