Gathering detailed insights and metrics for @json2csv/formatters
Gathering detailed insights and metrics for @json2csv/formatters
Gathering detailed insights and metrics for @json2csv/formatters
Gathering detailed insights and metrics for @json2csv/formatters
npm install @json2csv/formatters
Typescript
Module System
Node Version
NPM Version
100
Supply Chain
99.5
Quality
77.7
Maintenance
100
Vulnerability
100
License
TypeScript (94.51%)
JavaScript (5.49%)
Total Downloads
14,354,071
Last Day
6,859
Last Week
242,989
Last Month
1,022,810
Last Year
10,998,719
314 Stars
682 Commits
31 Forks
6 Watching
4 Branches
60 Contributors
Minified
Minified + Gzipped
Latest Version
7.0.6
Package Id
@json2csv/formatters@7.0.6
Unpacked Size
112.57 kB
Size
30.88 kB
File Count
87
NPM Version
10.2.4
Node Version
20.11.0
Publised On
11 Feb 2024
Cumulative downloads
Total Downloads
Last day
-19.6%
6,859
Compared to previous day
Last week
-5.8%
242,989
Compared to previous week
Last month
-6.6%
1,022,810
Compared to previous month
Last year
228.5%
10,998,719
Compared to previous year
No dependencies detected.
A formatter is function a used by json2csv
(in any of its flavours) to convert javascript values into plain text before adding it into the CSV as a cell.
Supported formatters are given by the types returned by typeof
:
undefined
boolean
number
bigint
string
symbol
function
object
And a special type that only applies to headers:
headers
Pay special attention to the string
formatter since other formatters like the headers
or object
formatters, rely on the string
formatter for the stringification of their value..
There are multiple flavours of json2csv where you can use formatters:
Parser
API and a new StreamParser
API which doesn't the conversion in a streaming fashion in pure js.Node Transform
and Node Async Parser
APIs for Node users.WHATWG Transform Stream
and WHATWG Async Parser
APIs for users of WHATWG streams (browser, Node or Deno).CLI
interface.There is a number of built-in formatters provided by this package.
1import { 2 default as defaultFormatter, 3 number as numberFormatter, 4 string as stringFormatter, 5 stringQuoteOnlyIfNecessary as stringQuoteOnlyIfNecessaryFormatter, 6 stringExcel as stringExcelFormatter, 7 symbol as symbolFormatter, 8 object as objectFormatter, 9} from '@json2csv/formatters';
This formatter just relies on standard JavaScript stringification.
This is the default formatter for undefined
, boolean
, number
and bigint
elements.
It's not a factory but the formatter itself.
1{ 2 undefined: defaultFormatter, 3 boolean: defaultFormatter, 4 number: defaultFormatter, 5 bigint: defaultFormatter, 6}
Format numbers with a fixed amount of decimals
The formatter needs to be instantiated and takes an options object as arguments containing:
separator
- String, separator to use between integer and decimal digits. Defaults to .
. It's crucial that the decimal separator is not the same character as the CSV delimiter or the result CSV will be incorrect.decimals
- Number, amount of decimals to keep. Defaults to all the available decimals.1{ 2 // 2 decimals 3 number: numberFormatter(), 4 5 // 3 decimals 6 number: numberFormatter(3) 7}
Format strings quoting them and escaping illegal characters if needed.
The formatter needs to be instantiated and takes an options object as arguments containing:
quote
- String, quote around cell values and column names. Defaults to "
.escapedQuote
- String, the value to replace escaped quotes in strings. Defaults to double-quotes (for example ""
).This is the default for string
elements.
1{
2 // Uses '"' as quote and '""' as escaped quote
3 string: stringFormatter(),
4
5 // Use single quotes `'` as quotes and `''` as escaped quote
6 string: stringFormatter({ quote: '\'' }),
7
8 // Never use quotes
9 string: stringFormatter({ quote: '' }),
10
11 // Use '\"' as escaped quotes
12 string: stringFormatter({ escapedQuote: '\"' }),
13}
The default string formatter quote all strings. This is consistent but it is not mandatory according to the CSV standard. This formatter only quote strings if they don't contain quotes (by default "
), the CSV separator character (by default ,
) or the end-of-line (by default \n
or \r\n
depending on you operating system).
The formatter needs to be instantiated and takes an options object as arguments containing:
quote
- String, quote around cell values and column names. Defaults to "
.escapedQuote
- String, the value to replace escaped quotes in strings. Defaults to 2xquotes
(for example ""
).eol
- String, overrides the default OS line ending (i.e. \n
on Unix and \r\n
on Windows). Ensure that you use the same eol
here as in the json2csv options.1{
2 // Uses '"' as quote, '""' as escaped quote and your OS eol
3 string: stringQuoteOnlyIfNecessaryFormatter(),
4
5 // Use single quotes `'` as quotes, `''` as escaped quote and your OS eol
6 string: stringQuoteOnlyIfNecessaryFormatter({ quote: '\'' }),
7
8 // Never use quotes
9 string: stringQuoteOnlyIfNecessaryFormatter({ quote: '' }),
10
11 // Use '\"' as escaped quotes
12 string: stringQuoteOnlyIfNecessaryFormatter({ escapedQuote: '\"' }),
13
14 // Use linux EOL regardless of your OS
15 string: stringQuoteOnlyIfNecessaryFormatter({ eol: '\n' }),
16}
Converts string data into normalized Excel style data after formatting it using the given string formatter.
The formatter needs to be instantiated and takes no arguments.
1{ 2 string: stringExcelFormatter, 3}
Format the symbol as its string value and then use the given string formatter i.e. Symbol('My Symbol')
is formatted as "My Symbol"
.
The formatter needs to be instantiated and takes an options object as arguments containing:
stringFormatter
- String formatter to use to stringify the symbol name. Defaults to the built-in stringFormatter
.This is the default for symbol
elements.
1{ 2 // Uses the default string formatter 3 symbol: symbolFormatter(), 4 5 // Uses custom string formatter 6 // You rarely need to this since the symbol formatter will use the string formatter that you set. 7 symbol: symbolFormatter(myStringFormatter()), 8}
Format the object using JSON.stringify
and then the given string formatter.
Some object types likes Date
or Mongo's ObjectId
are automatically quoted by JSON.stringify
. This formatter, remove those quotes and uses the given string formatter for correct quoting and escaping.
The formatter needs to be instantiated and takes an options object as arguments containing:
stringFormatter
- tring formatter to use to stringify the symbol name. Defaults to our built-in stringFormatter
.This is the default for function
and object
elements. function
's are formatted as empty ``.
1{
2 // Uses the default string formatter
3 object: objectFormatter(),
4
5 // Uses custom string formatter
6 // You rarely need to this since the object formatter will use the string formatter that you set.
7 object: objectFormatter(myStringFormatter()),
8}
Users can create their own formatters as simple functions.
1function formatType(itemOfType) { 2 // format type 3 return formattedItem; 4}
or using ES6
1const formatType = (itemOfType) => { 2 // format type 3 return itemOfType; 4};
For example, let's format functions as their name or 'unknown'.
1const functionNameFormatter = (item) => item.name || 'unknown';
Then you can add { function: functionNameFormatter }
to the formatters
object.
A less trivial example would be to ensure that string cells never take more than 20 characters.
1const fixedLengthStringFormatter = (stringLength, ellipsis = '...') => 2 (item) => 3 item.length <= stringLength 4 ? item 5 : `${item.slice(0, stringLength - ellipsis.length)}${ellipsis}`;
Then you can add { string: fixedLengthStringFormatter(20) }
to the formatters
object.
Or fixedLengthStringFormatter(20, '')
to not use the ellipsis and just clip the text.
As with the sample transform in the previous section, the reason to wrap the actual formatter in a factory function is so it can be parameterized easily.
Keep in mind that the above example doesn't quote or escape the string which is problematic. A more realistic example could use our built-in string formatted to do the quoting and escaping like:
1import { string as defaultStringFormatter } from 'json2csv/formatters';
2
3const fixedLengthStringFormatter = (stringLength, ellipsis = '...', stringFormatter = defaultStringFormatter()) =>
4 (item) =>
5 item.length <= stringLength
6 ? item
7 : stringFormatter(`${item.slice(0, stringLength - ellipsis.length)}${ellipsis})`;
Formatters are configured in the formatters
option when creating a parser.
1import { Parser } from '@json2csv/plainjs'; 2import { number as numberFormatter } from '@json2csv/formatters'; 3import { fixedLengthStringFormatter } from './custom-formatters'; 4 5try { 6 const opts = { 7 formatters: { 8 number: numberFormatter({ decimals: 3, separator: ',' }), 9 string: fixedLengthStringFormatter(20) 10 } 11 }; 12 const parser = new Parser(opts); 13 const csv = parser.parse(myData); 14 console.log(csv); 15} catch (err) { 16 console.error(err); 17}
At the moment, only some options of the string
built-in formatters are supported by the CLI interface.
1$ json2csv -i input.json --quote '"' --escaped-quote '\"'
or if you want to use the String Excel
instead:
1$ json2csv -i input.json --excel-strings
See https://juanjodiaz.github.io/json2csv/#/advanced-options/formatters.
See LICENSE.md.
No vulnerabilities found.
No security vulnerabilities found.