Giter VIP home page Giter VIP logo

csv.js's Introduction

CSV.js

Simple, ultra light (10kb uncompressed) javascript CSV library for browser and node with zero dependencies.

Originally developed as part of ReclineJS but now fully standalone.

Usage

Grab the csv.js file and include it in your application.

Depends on jQuery or underscore.deferred (for deferred) in fetch (and jQuery if you need ajax). parse and serialize have zero dependencies.

fetch

A convenient way to load a CSV file from various different sources. fetch supports 3 options depending on the attribute provided on the info argument:

CSV.fetch({
    data: 'raw csv string'
    // or ...
    url: 'url to a csv file'
    // or ...
    file: an HTML 5 file object

    // optional options about structure of the CSV file
    // following the CSV Dialect Description Format 
    // https://frictionlessdata.io/specs/csv-dialect/
    dialect: {
      ...
    }
  }
).done(function(dataset) {
  // dataset object doc'd below
  console.log(dataset);
});

Some more detail on the argument object:

  • data is a string in CSV format. This is passed directly to the CSV parser
  • url: a url to an online CSV file that is ajax accessible (note this usually requires either local or on a server that is CORS enabled). The file is then loaded using jQuery.ajax and parsed using the CSV parser (NB: this requires jQuery) All options generates similar data and use the memory store outcome, that is they return something like:
  • file: is an HTML5 file object. This is opened and parsed with the CSV parser.
  • dialect: hash / dictionary following the same structure as for parse method below.

Returned dataset object looks like:

{
  // an array of arrays - one array each row in the CSV
  // (excluding header row - i.e. first row)
  records: [ [...], [...], ... ],
  // list of fields
  fields: [ 'field-name-1', 'field-name-2', ... ],
  metadata: { may be some metadata e.g. file name }
}

Raw parsing

var out = CSV.parse(csvString, dialect);

Converts a Comma Separated Values string into an array of arrays. Each line in the CSV becomes an array.

Empty fields are converted to nulls and non-quoted numbers are converted to integers or floats.

  • csvString: the csv string to parse

  • dialect: [optional] hash with keys as per the CSV dialect description format. It also supports the following additional keys:

    • skipInitialRows: [optional] integer number of rows to skip (default 0)

    For backwards compatability with earlier versions of the library the dialect also supports the following:

Serialize

Convert an Object or a simple array of arrays into a Comma Separated Values string.

var out = CSV.serialize(dataToSerialize, dialect);

Returns a string representing the array serialized as a CSV.

dataToSerialize is an Object or array of arrays to convert. Object structure must be as follows:

{
  fields: [ {id: .., ...}, {id: ..., 
  records: [ { record }, { record }, ... ]
  ... // more attributes we do not care about
}

Nulls are converted to empty fields and integers or floats are converted to non-quoted numbers.

You may optionally specify a label inside each field so that the serialized data will use it as the column heading instead of the id.


Other JS CSV Libs

Node

Development

Requirements

  • webpack
  • jquery
npm install
npm install jquery
webpack-dev-server

Run tests

Requirements

  • karma
  • phantomjs
npm -g install karma karma-cli phantomjs-prebuilt
npm install
npm install jquery
npm test

csv.js's People

Contributors

rufuspollock avatar topicus avatar starsinmypockets avatar brysgo avatar timwis avatar

Stargazers

Eugene avatar  avatar Shreyas Murali avatar Roki avatar hata6502 avatar Abdurrahman Fadhil avatar Patrick Connolly avatar Oliver avatar Code Boxx avatar 1 7 3 dup rot avatar Rochak Chauhan avatar Matt Hall avatar Xin avatar Lydia avatar Michael Dobekidis avatar  avatar Tu Hoang Minh avatar  avatar Andrew Gurylev avatar  avatar Dunkan avatar Roj avatar James White avatar  avatar Rafał Mikołajun avatar Nikolay avatar Ednardo Gomes avatar Paulo Victor avatar  avatar Luca Liberati avatar  avatar Damien Golding avatar Ahmad Karim avatar Konrad Gadzinowski avatar Bes avatar Prayag Verma  avatar Simon JAILLET avatar  avatar  avatar Clayton Marshall avatar  avatar Hai Nguyen Quang avatar Remco Tolsma avatar Ewetumo Alexander avatar Wout avatar  avatar Ikbel avatar Gerard Parareda avatar Muhammad Sholeh avatar  avatar  avatar Lukas Bachschwell avatar Huy Cuong Nguyen avatar Gabriel Chung avatar Christian Meichsner avatar Shubhendu avatar jeremy buller avatar John Dave Manuel avatar Muhammad Farid Zia avatar Michel Moreau avatar  avatar Robert avatar Lawrence Ching avatar Kerberos avatar Vinicius Meng avatar Spencer avatar Marat Komarov avatar  avatar JayChung avatar xiongwilee avatar Ivan Wang avatar Welcome to Yingxin's GitHub page. avatar Borodin Dmitry avatar noa avatar Ibrahim H. avatar ruans avatar Hongkun Xu avatar Fazlur Rahman avatar Matt Walker avatar ants avatar Dileep avatar ap avatar  avatar Jon Repp avatar Martinez Andres avatar Cristian Martinez avatar Harvey Kandola avatar E-Tiger Studio avatar  avatar  avatar Mcdonoughd avatar Luiz Filho avatar Divine avatar Zafpyr avatar  avatar Michael avatar  avatar Chen avatar Ezekiel avatar Hani Gamal avatar

Watchers

 avatar Darwin Peltan avatar Edgar Z. Alvarenga avatar Spencer Tom Tafadzwa Chirume avatar  avatar James Cloos avatar Anders avatar Michael Bauer avatar Sam Leon avatar Ira avatar Jonathan Gray avatar Stephen Abbott Pugh avatar Yamini avatar  avatar Andres Vazquez avatar Nikesh Balami avatar Shashi Gharti avatar Oscar Montiel avatar Patricio Del Boca avatar  avatar  avatar Cédric Lombion avatar Lucas Pretti avatar Georgiana Bere avatar  avatar Jan avatar  avatar

csv.js's Issues

Reject fetch promise when the ajax request fails

Since the fetch promise is not being rejected when the ajax call fails then I didn't find a way to handle request errors.

It would be nice to do something like this:

CSV.fetch(dataset)
  .done(function(data){....})
  .fail(function(error){ console.log(error); });

Working in a PR.

unable to make it RFC

I was trying to make it closer to RFC, but realized that parsing is used default values. So if I have CSV pipe delimited like
A|B|C
There is no way to pass custom options due to a bug: while m.parse takes options from which it takes delimiter, those options are internal hardcoded
image

In 'fetch' method there is no way to pass custom options to override delimiter with own
image

While can pass custom dialect/options to serialize, the parse options are hardcoded in my.normalizeDialectOptions

Uncaught TypeError: this._store.query is not a function in recline model using csv backend

We are using the recline library to instantiate a csv backend to generate charts using nvd3, however I am getting an error that I do not understand:

Uncaught TypeError: this._store.query is not a function

The error is coming from the recline model on line 201 (the dataset->query method):

this._store.query(actualQuery, this.toJSON()) ...

The dataset instance in question is using the csv backend, which (when I output it to the console on model init) does not seem to have a query method set on it. Consequently, when this._store is set to backend by the dataset model there is no query method and the above error is thrown.

I'm unclear why I'm seeing this behavior and am wondering if anyone has any insight.

Dialect options are ignored when parsing

You are passing the dataset to the parse function, but it assumes you get the dialect hash, so it will not reach down from the dataset to the dialect hash so the dialect options are ignored and the default options are used.
FIX1: Rename parse function argument dialect to dataset and create local variable dialect from the dataset
FIX2: Pass dialect hash to parse function

Shipped csv.min.js is out of date

The csv.min.js on the master branch hasn't been updated since commit 5cb7c7 in 2016. There have been a couple of changes to csv.js since then that I was surprised weren't reflected in the minified version.

CSV parser should respect escaped quotes

Originally from @amercader here datopian/datahub#304.

The background for this is trying to store a GeoJSON string in a CSV to display it on the map view. Recline won't parse this correctly:

name,geom
Test, "{\"type\":\"Point\",\"coordinates\":[-1.1207,45.4874]}"

The following will work, but it is not always possible to define the text delimiter, eg in CKAN (Note the single quote):

name,geom
Test, '{"type":"Point","coordinates":[-1.1207,45.4874]}'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.