Gathering detailed insights and metrics for json-2-csv
Gathering detailed insights and metrics for json-2-csv
Gathering detailed insights and metrics for json-2-csv
Gathering detailed insights and metrics for json-2-csv
npm install json-2-csv
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
423 Stars
424 Commits
58 Forks
8 Watching
3 Branches
22 Contributors
Updated on 26 Nov 2024
Minified
Minified + Gzipped
TypeScript (98.37%)
JavaScript (1.63%)
Cumulative downloads
Total Downloads
Last day
-5.6%
79,430
Compared to previous day
Last week
4.7%
464,658
Compared to previous week
Last month
10%
1,917,311
Compared to previous month
Last year
123.8%
15,546,928
Compared to previous year
Convert JSON to CSV or CSV to JSON
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.
1$ npm install json-2-csv
CLI:
1$ npm install @mrodrig/json-2-csv-cli
Upgrading to v5 from v4? Check out the upgrade guide.
1let converter = require('json-2-csv'); 2const csv = await converter.json2csv(data, options);
or
1import { json2csv } from 'json-2-csv';
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?
false
checkSchemaDifferences
- Boolean - Should all documents have the same schema?
false
true
.delimiter
- Document - Specifies the different types of delimiters
field
- String - Field Delimiter.
,
wrap
- String - Wrap values in the delimiter of choice (e.g. wrap values in quotes).
"
eol
- String - End of Line Delimiter.
\n
emptyFieldValue
- Any - Value that, if specified, will be substituted in for field values that are undefined
, null
, or an empty string.
escapeHeaderNestedDots
- Boolean - Should nested dots in header keys be escaped?
true
1[ 2 { 3 "a.a": "1" 4 } 5]
true
will generate the following CSV:1a\.a 21
false
will generate the following CSV:1a.a 21
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).
[]
unwindArrays
, arrays present at excluded key paths will not be unwound.expandNestedObjects
- Boolean - Should nested objects be deep-converted to CSV?
true
1[ 2 { 3 "make": "Nissan", 4 "model": "Murano", 5 "year": 2013, 6 "specifications": { 7 "mileage": 7106, 8 "trim": "S AWD" 9 } 10} 11]
true
uses the following keys:
['make', 'model', 'year', 'specifications.mileage', 'specifications.trim']
false
uses the following keys:
['make', 'model', 'year', 'specifications']
expandArrayObjects
- Boolean - Should objects in array values be deep-converted to CSV?
false
1[ 2 { 3 "specifications": [ 4 { "features": [...] }, 5 { "mileage": "5000" } 6 ] 7 } 8]
true
uses the following keys:
['specifications.features', 'specifications.mileage']
false
uses the following keys:
['specifications']
keys
- Array - Specify the keys that should be converted.
1{ 2 "field": "string", // required 3 "title": "string", // optional 4 "wildcardMatch": false, // optional - default: false 5}
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.[ 'key1', 'key2', ... ]
[ 'key1', { field: 'key2', wildcardMatch: true }]
[ { field: 'key1', title: 'Key 1' }, { field: 'key2' }, 'key3', ... ]
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.
useDateIso8601Format
and useLocaleFormat
.prependHeader
- Boolean - Should the auto-generated header be prepended as the first line in the CSV?
true
sortHeader
- Boolean or Function - Should the header keys be sorted in alphabetical order? or pass a function to use a custom sorting function
false
trimFieldValues
- Boolean - Should the field values be trimmed?
false
trimHeaderFields
- Boolean - Should the header fields be trimmed?
false
unwindArrays
- Boolean - Should array values be "unwound" such that there is one line per value in the array?
false
1[ 2 { 3 "_id": {"$oid": "5cf7ca3616c91100018844af"}, 4 "data": {"category": "Computers", "options": [{"name": "MacBook Pro 15"}, {"name": "MacBook Air 13"}]} 5 }, 6 { 7 "_id": {"$oid": "5cf7ca3616c91100018844bf"}, 8 "data": {"category": "Cars", "options": [{"name": "Supercharger"}, {"name": "Turbocharger"}]} 9 } 10]
true
will unwind the JSON to four objects, and therefore four lines of CSV values:1_id.$oid,data.category,data.options.name
25cf7ca3616c91100018844af,Computers,MacBook Pro 15
35cf7ca3616c91100018844af,Computers,MacBook Air 13
45cf7ca3616c91100018844bf,Cars,Supercharger
55cf7ca3616c91100018844bf,Cars,Turbocharger
false
will leave the values unwound and will convert the array as-is (when this option is used without expandArrayObjects):1_id.$oid,data.category,data.options 25cf7ca3616c91100018844af,Computers,"[{""name"":""MacBook Pro 15""},{""name"":""MacBook Air 13""}]" 35cf7ca3616c91100018844bf,Cars,"[{""name"":""Supercharger""},{""name"":""Turbocharger""}]"
useDateIso8601Format
- Boolean - Should date values be converted to an ISO8601 date string?
false
toISOString()
rather than toString()
or toLocaleString()
depending on the other options provided.useLocaleFormat
- Boolean - Should values be converted to a locale specific string?
false
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.
false
preventCsvInjection
- Boolean - Should CSV injection be prevented by left trimming these characters: Equals (=), Plus (+), Minus (-), At (@), Tab (0x09), Carriage return (0x0D).
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 CSVoptions
- (Optional) A JSON document specifying any of the following key value pairs:
delimiter
- Document - Specifies the different types of delimiters
field
- String - Field Delimiter.
,
wrap
- String - The character that field values are wrapped in.
"
eol
- String - End of Line Delimiter.
\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?
false
headerFields
- Array - Specify the field names (as strings) in place of a header line in the CSV itself.
{info : {name: 'Mike'}}
), then use .
characters in the string to denote a nested field, like ['info.name']keys
- Array - Specify the keys (as strings) that should be converted.
null
{info : {name: 'Mike'}}
), then set this to ['info.name']
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.
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?
false
trimFieldValues
- Boolean - Should the field values be trimmed?
false
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:
1$ npm install @mrodrig/json-2-csv-cli
Usage: json2csv <jsonFile> [options]
Arguments:
jsonFile JSON file to convert
Options:
-V, --version output the version number
-o, --output [output] Path of output file. If not provided, then stdout will be used
-a, --array-indexes-as-keys Includes array indexes in the generated keys
-S, --check-schema Check for schema differences
-f, --field <delimiter> Field delimiter
-w, --wrap <delimiter> Wrap delimiter
-e, --eol <delimiter> End of Line delimiter
-E, --empty-field-value <value> Empty field value
-n, --expand-nested-objects Expand nested objects to be deep converted to CSV
-k, --keys [keys] Keys of documents to convert to CSV
-d, --escape-header-nested-dots Escape header nested dots
-b, --excel-bom Excel Byte Order Mark character prepended to CSV
-x, --exclude-keys [keys] Comma separated list of keys to exclude
-A, --expand-array-objects Expand array objects
-W, --without-header Withhold the prepended header
-p, --prevent-csv-injection Prevent CSV Injection
-s, --sort-header Sort the header fields
-F, --trim-fields Trim field values
-H, --trim-header Trim header fields
-U, --unwind-arrays Unwind array values to their own CSV line
-I, --iso-date-format Use ISO 8601 date format
-L, --locale-format Use locale format for values
-B, --wrap-booleans Wrap booleans
-h, --help display help for command
Usage: csv2json <csvFile> [options]
Arguments:
csvFile CSV file to convert
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> Field delimiter
-w, --wrap <delimiter> Wrap delimiter
-e, --eol <delimiter> End of Line delimiter
-b, --excel-bom Excel Byte Order Mark character prepended to CSV
-p, --prevent-csv-injection Prevent CSV Injection
-F, --trim-fields Trim field values
-H, --trim-header Trim header fields
-h, --header-fields Specify the fields names in place a header line in the CSV itself
-k, --keys [keys] Keys of documents to convert to CSV
--help display help for command
1$ npm test
To see test coverage, please run:
1$ npm run coverage
csv2json test.csv -o output.json
json2csv test.json -o output.csv -W -k arrayOfStrings -o output.csv
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
10 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 9
Reason
1 existing vulnerabilities detected
Details
Reason
Found 4/12 approved changesets -- score normalized to 3
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More