3.2.0 • Published 3 years ago

jsonexport v3.2.0

Weekly downloads
168,546
License
Apache-2.0
Repository
github
Last release
3 years ago

jsonexport {} → 📄

Travis Known Vulnerabilities NPM Version NPM Downloads NPM Downloads NPM License GitHub stars Try jsonexport on RunKit npm bundle size

easy to use 👌 (should work as expected without much customization)️

extendable 🕺 (many options to customize the output)

✔️ tiny 🐜 (0 dependencies)

scalable 💪 (works with big files using Streams)

fast

Project Page

Online Demo Page

Usage

Installation command is npm install jsonexport.

Run tests with npm test.

const jsonexport = require('jsonexport');

jsonexport({lang: 'Node.js', module: 'jsonexport'}, {rowDelimiter: '|'}, function(err, csv){
    if (err) return console.error(err);
    console.log(csv);
});

CLI

Global installation command is npm install -g jsonexport.

Convert JSON to CSV using cat data.json | jsonexport or jsonexport data.json

Usage: jsonexport <JSON filename> <CSV filename>

Browser

Use the code in the folder named dist to run jsonexport in the browser

Browser Import Examples

Webpack

const jsonexport = require("jsonexport/dist")

Typescript

import * as jsonexport from "jsonexport/dist"

Stream

const jsonexport = require('jsonexport');
const fs = require('fs');

const reader = fs.createReadStream('data.json');
const writer = fs.createWriteStream('out.csv');

reader.pipe(jsonexport()).pipe(writer);

Promise

const jsonexport = require('jsonexport')
try {
    const csv = await jsonexport({lang: 'Node.js', module: 'jsonexport'}, {rowDelimiter: '|'});
} catch (err) {
    console.error(err);
}

JSON Array Example

Simple Array

Code

const jsonexport = require('jsonexport');

const contacts = [{
    name: 'Bob',
    lastname: 'Smith'
},{
    name: 'James',
    lastname: 'David'
},{
    name: 'Robert',
    lastname: 'Miller'
},{
    name: 'David',
    lastname: 'Martin'
}];

jsonexport(contacts, function(err, csv){
    if (err) return console.error(err);
    console.log(csv);
});

Result

name,lastname
Bob,Smith
James,David
Robert,Miller
David,Martin

Complex Array

Code

const jsonexport = require('jsonexport');

const contacts = [{
   name: 'Bob',
   lastname: 'Smith',
   family: {
       name: 'Peter',
       type: 'Father'
   }
},{
   name: 'James',
   lastname: 'David',
   family:{
       name: 'Julie',
       type: 'Mother'
   }
},{
   name: 'Robert',
   lastname: 'Miller',
   family: null,
   location: [1231,3214,4214]
},{
   name: 'David',
   lastname: 'Martin',
   nickname: 'dmartin'
}];

jsonexport(contacts, function(err, csv){
    if (err) return console.error(err);
    console.log(csv);
});

Result

name,lastname,family.name,family.type,family,location,nickname
Bob,Smith,Peter,Father
James,David,Julie,Mother
Robert,Miller,,,,1231;3214;4214
David,Martin,,,,,dmartin

JSON Object Example

Simple Object

Code

const jsonexport = require('jsonexport');

const stats = {
    cars: 12,
    roads: 5,
    traffic: 'slow'
};

jsonexport(stats, function(err, csv){
    if(err) return console.error(err);
    console.log(csv);
});

Result

cars,12
roads,5
traffic,slow

Complex Object

Code

const jsonexport = require('jsonexport');

const stats = {
    cars: 12,
    roads: 5,
    traffic: 'slow',
    speed: {
        max: 123,
        avg: 20,
        min: 5
    },
    size: [10,20]
};

jsonexport(stats, function(err, csv){
    if(err) return console.error(err);
    console.log(csv);
});

Result

cars,12
roads,5
traffic,slow
speed.max,123
speed.avg,20
speed.min,5
size,10;20

Options

In order to get the most of out of this module, you can customize many parameters and functions.

  • headerPathString - String Used to create the propriety path, defaults to . example contact: {name: 'example} = contact.name
  • fillGaps - Boolean Set this option if don't want to have empty cells in case of an object with multiple nested items (array prop), defaults to false Issue #22
  • fillTopRow - Boolean try filling top rows first for unpopular colums, defaults to false
  • headers - Array Used to set a custom header order, defaults to [] example ['lastname', 'name']
  • rename - Array Used to set a custom header text, defaults to [] example ['Last Name', 'Name']
  • mapHeaders - Function Post-process headers after they are calculated with delimiters, example mapHeaders: (header) => header.replace(/foo\./, '')
  • rowDelimiter - String Change the file row delimiter
    • Defaults to , (cvs format).
    • Use \t for xls format.
    • Use ; for (windows excel .csv format).
  • textDelimiter - String The character used to escape the text content if needed (default to ")
  • forceTextDelimiter - Boolean Set this option to true to wrap every data item and header in the textDelimiter. Defaults to false
  • endOfLine - String Replace the OS default EOL.
  • mainPathItem - String Every header will have the mainPathItem as the base.
  • arrayPathString - String This is used to output primitive arrays in a single column, defaults to ;
  • booleanTrueString - String Will be used instead of true.
  • booleanFalseString - String Will be used instead of false.
  • includeHeaders - Boolean Set this option to false to hide the CSV headers.
  • undefinedString - String If you want to display a custom value for undefined strings, use this option. Defaults to .
  • verticalOutput - Boolean Set this option to false to create a horizontal output for JSON Objects, headers in the first row, values in the second.
  • typeHandlers - {typeName:(value, index, parent)=>any A key map of constructors used to match by instance to create a value using the defined function (see example)

typeHandlers

Define types by constructors and what function to run when that type is matched

const jsonexport = require('jsonexport');

//data
const contacts = {
  'a' : Buffer.from('a2b', 'utf8'),
  'b' : Buffer.from('other field', 'utf8'),
  'x' : 22,
  'z' : function(){return 'bad ace'}
};

const options = {
  //definitions to type cast
  typeHandlers: {
    Array:function(value,index,parent){
      return 'replaced-array';
    },
    Boolean:function(value,index,parent){
      return 'replaced-boolean';
    },
    Function:function(value,index,parent){
      return value();
    },
    Number:function(value,index,parent){
      return 'replaced-number';
    },
    String:function(value,index,parent){
      return 'replaced-string';
    },
    Buffer:function(value,index,parent){
      return value.toString();
    }
  }
};

jsonexport(contacts, options, function(err, csv) {
  if (err) return console.error(err);
  console.log(csv);
});

The output would be:

a,a2b
b,other field
x,replaced-number
z,bad ace

Date typeHandler?

var date = new Date();
jsonexport({
    a: date,
    b: true
}, {
    typeHandlers: {
        Object: (value, name) => {
            if (value instanceof Date) return date.toLocaleString();
            return value;
        }
    }
}, (err, csv) => {
    if (err) return console.error(err);
    console.log(csv);
});

When using typeHandlers, Do NOT do this

const options = {
  typeHandlers: {
    Object:function(value, index, parent){
      return 'EVERYTHING IS AN OBJECT';
    }
  }
};

It is NOT an error, however the recursive result becomes illegable functionality strings

Contributors

@mochilabs/ra-ui-materialuifieldflint@4lch4/dtaid@infinitebrahmanuniverse/nolb-jsone@everything-registry/sub-chunk-1987simple-json-to-csvshellenergy-csvdigicust_helperssb-dashletssb-dashlets-testsb-dashlet-v10sb-dashlet-v11sb-dashlet-v12sb-dashlet-v13sb-dashlet-v13-msb-dashlet-v9-testsplurtspringmicro-photo-gallerydocker-my-app@aviato/ui@based/edge-server@based/server@beazergood/csv-streams@cdmsmith/graphiqlcloudcms-util@cguillot/dim_armor-notes_cli@cloudbase/weda-uicdm-trade-viewcdm-trades-commoncdn-cache-checkcarousel_comp_five@arvindr21/xray-clibt-corebt-ui-materialui@colombalink/baseduicsvjsonconveror@datarailsshared/ai-service-typesddf-validationautowebperfterminal-stocksterminalfootballespn-play-by-play-scrapereztranslateweda-model-components@helms/weda-businessapicrud-uifantasy-f1-analyzerfalcon-defifast-submission2csvfolkvangrfreshdesk-clientjira-xledgerwren-8080ktbl-apistushangovinfo-link-jsvsdkjson2csvtreat-nft-json-datagithub-resource-convertertrack-trace-toolsglobal-swapvalhalla-erc20valhalla-villazbtocsvwarpheadhuntervoiceflowmyvariantjsmv-tmp-coremv-tmp-ui-materialuiyamQuery-excelmasteos-ra-ui-materialuimetaxot-contract@jeff-tian/mongo-csv@jdxconsulting/cdm-trades-common@jbruni/linkinator@kampaay/ra-core@kampaay/ra-ui-materialui@jupiterone/clilinkinator-css-editionlisa.csv.parser.jsloader-service@mikejestes/ra-ui-materialui@mikejestes/ra-ui-materialui-fork@elbabass/ra-data-rest-clientportofino-react-adminpostgis-preview@mindha-us/penguinserver@mkven/ra-conditions@modalnetworks/rpacorenode-red-contrib-json2csvpeacetrue-react-admin@project-sunbird/sb-dashlet-v9@project-sunbird/sb-dashlet-v14projectlky-koa-client@sablelab/pricing-calculator@ryus08/penguinserver@fomobro/fomo-core@fomobro/fomobot@seasons/ra-ui-materialui
3.2.0

3 years ago

3.1.0

3 years ago

3.0.1

4 years ago

3.0.0

4 years ago

2.5.2

4 years ago

2.4.2

4 years ago

2.5.1

4 years ago

2.3.1

4 years ago

2.5.0

4 years ago

2.4.1

5 years ago

2.3.0

6 years ago

2.2.1

6 years ago

2.2.0

6 years ago

2.1.0

6 years ago

2.0.11

7 years ago

2.0.10

7 years ago

2.0.9

7 years ago

2.0.8

7 years ago

2.0.7

7 years ago

2.0.6

7 years ago

2.0.4

7 years ago

2.0.2

7 years ago

2.0.1

7 years ago

2.0.0

7 years ago

1.5.2

7 years ago

1.5.1

7 years ago

1.5.0

7 years ago

1.4.2

7 years ago

1.3.2

8 years ago

1.3.1

8 years ago

1.3.0

8 years ago

1.2.1

8 years ago

1.2.0

8 years ago

1.1.2

8 years ago

1.1.0

8 years ago

1.0.7

8 years ago

1.0.6

9 years ago

1.0.5

9 years ago

1.0.4

9 years ago

1.0.3

9 years ago

1.0.2

9 years ago

1.0.1

9 years ago

1.0.0

9 years ago