npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

json2csvexporter

v0.5.1

Published

A simple JSON to CSV converter.

Downloads

554

Readme

json2csvexporter

This is a simple little library for exporting simple JSON structures to a CSV file. The download will trigger the user to save the file to their system. The library itself does not handle any File I/O.

Currently, json2csvexporter does not support nested JSON data. As such, you will probably need to reduce complex structures into a simple key: value schema.

To install:

npm i json2csvexporter --save

Provided are:

  • umd-formatted file: dist/CSVExportService.js (browser-ready)
  • commonjs-formatted file: lib/CSVExportService.js
  • es-module: module/CSVExportService.js

Table of contents:

  1. Simple Example
  2. Example with Custom Options
  3. Example with TSV and Formatters
  4. JSON to CSV/TSV encoded String/Blob (without downloading on the client)
  5. API and Options Docs
  6. Browsers Support
  7. Contributing

Simple Example

In this simple example we take a JSON object and print all of the properties in it to the CSV. There is also an online demo available via CodeSandbox.

import CSVExportService from 'json2csvexporter';
...
const vehiclesJSON = [
  {id: 1, make: 'Toyota', model: 'Corolla', year: 2014},
  {id: 2, make: 'Ford', model: 'Mustang', year: 2012},
  {id: 3, make: 'Toyota', model: '', year: ''}
];
const exporter = CSVExportService.create();
exporter.downloadCSV(vehiclesJSON);

This will generate the following CSV:

id,make,model,year
1,Toyota,Corolla,2014
2,Ford,Mustang,2012
3,Toyota,,

Example with Custom Options

In this example, we will take the same JSON object from the previous example, but only print a list of properties that we want. We will also decorate the headers with different names.

import CSVExportService from 'json2csvexporter';
...
const csvColumnsList = ['id', 'make', 'model', 'year'];
const csvColumnsMap = {
  id: 'ID',
  make: 'Make',
  model: 'Model Name',
  year: 'Year'
};
const vehiclesJSON = [
  {id: 1, make: 'Toyota', model: 'Corolla', year: 2014},
  {id: 2, make: 'Ford', model: 'Mustang', year: 2012},
  {id: 3, make: 'Toyota', model: '', year: ''}
];
const exporter = CSVExportService.create({
  columns: csvColumnsList,
  headers: csvColumnsMap,
  includeHeaders: true,
});
exporter.downloadCSV(vehiclesJSON);

This will generate the following CSV:

ID,Make,Model Name,Year
1,Toyota,Corolla,2014
2,Ford,Mustang,2012
3,Toyota,,

Example with TSV and Formatters

In this example, we will make a TSV file and create formatting functions to style the content of certain properties.

import CSVExportService from 'json2csvexporter';
...
// using the same vehiclesJSON as before...

const exporter = CSVExportService.create({
  contentType: 'text/tsv',
  filename: 'newformat.tsv',
  delimiter: '\t',
  formatters: {
    id: (id) => {
      return `#${id}`;
    },
    model: (model) => {
      return model || 'Unknown model';
    },
    year: (year) => {
      return year || 'Unknown year';
    }
  }
});
exporter.downloadCSV(vehiclesJSON);

This will generate the following TSV:

id  make  model year
#1  Toyota  Corolla 2014
#2  Ford  Mustang 2012
#3  Toyota  Unknown model  Unknown year

JSON to CSV/TSV encoded String/Blob (without downloading on the client)

import CSVExportService from 'json2csvexporter';
...
const vehiclesJSON = [
  {id: 1, make: 'Toyota', model: 'Corolla', year: 2014},
  {id: 2, make: 'Ford', model: 'Mustang', year: 2012},
  {id: 3, make: 'Toyota', model: '', year: ''}
];
const exporter = CSVExportService.create();
exporter.dataToString(vehiclesJSON);

This will return the CSV as a JavaScript String. This allows you to further manipulate the data, save to a file, a database or anything else.

Similarly, calling:

exporter.createCSVBlob(vehiclesJSON);

Will return a Blob {size: 76, type: "text/csv"}, or in other words, a regular JavaScript blob object that is encoded as the type you specified (in this case a plain text/csv). You then manipulate this Blob object however you like.

API and Options Docs

Options

When creating a new CSVExportService you can pass in an options objects. These are the options that you can use:

  • columns: an Array of Strings. Each element represents a property of the JSON object that should be extracted. If it is not provided, then the exporter will iterate through all of the properties.

  • contentType: the content type of the file. Default is text/csv

  • delimiter: the delimiter to separate values. The default is a comma.

  • formatters: an Object. Each property defines how to format a value corresponding to the same key.

  • headers: an Object. Works as a map to stylize keys in the header. E.g. {firstName: 'First Name'}

  • includeHeaders: a Boolean. Defaults to true.

  • devMode: a Boolean. Useful for debugging. Defaults to false.

API

The CSVExportService implements two static methods: create(options) which returns a new instance of CSVExportService and download(data, options) which initializes a new service and downloads the data right away.

For more info, dive into the code. It is a very simple class.

Browsers Support

| IE / Edge | Firefox | Chrome | Safari | Opera | iOS Safari | | --------- | --------- | --------- | --------- | --------- | --------- | | IE10, IE11, Edge| 4+ | 13+ | 5+ | 12+ | 7+ |

Contributing

  1. Submit issues or suggest features.
  2. Send PRs with bug fixes, tests, new methods, better docs etc.
  3. Share the love!

Contributor list

  1. @filipdanic
  2. @androidfanboi
  3. @erickzhao
  4. @bira91