• Stars
    star
    271
  • Rank 151,717 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 13 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A tiny library to fetch relational CSV data at client-side just like JSON

csonv.js

A tiny library to fetch relational CSV data at client-side just like JSON

Introduction

Simplicity within web development is searching its way towards the client-side. With the power of Javascript, we are able to get further and further. A great example is DocumentCloud’s Backbone.js and Alex MacCaw’s Spine. Not only do they provide a lot of great features, but they are also compact (3.9kb and 2K respectively when compressed) and it’s installation (including the hosting system) is just a matter of copying the Javascript sources. So there is no need to install any server-side scripting software whatsoever.

With keeping simplicity in mind, I have created csonv.js which serves CSV data like JSON. I have chosen CSV because it’s very straightforward:

  • a file represents a certain entity (equivalent to database tables)
  • the CSV format is far less complex than the XML format
  • CSV files consists of columns and rows which resembles attributes and records respectively
  • there is no need to install extra software on the hosting server (unlike MySQL or SQLite databases)

Please note that it is also possible to nest relational data within the resulting objects as if you are joining SQL tables.

I am aware that there are a couple of cons regarding this setup. But as I am a passionate Ruby and Javascript programmer, I have build csonv.js for the sake of fun and exploring side-steps like this one! ^^

Installation

Just include csonv.js:

  <script src="path/to/csonv.js" type="text/javascript"></script>

Note: include csonv.min.js for the minified csonv.js library

Usage

Providing the CSV data

Requirements

Make sure you have hosted the CSV files on a public location. A CSV file has to satisfy the following:

  • the first row has to contain keys – equivalent to attribute names
  • the second row has to describe the value types – equivalent to data types
  • the following rows have to represent the entries – equivalent to records

The data types available are:

  • string or an array of strings
  • integer or an array of integers
  • float or an array of floats
  • boolean or an array of booleans (options are: <empty>, 0 or 1)
  • date or an array of dates (RFC2822 or ISO8601)

There are two separators which csonv.js handles:

  • Csonv.separators.column (default: ";") – Used to separate columns
  • Csonv.separators.array (default: ",") – Used to separate array values

You can change the separators by assigning a custom one:

  <script>
    Csonv.separators.column = "|";
    Csonv.separators.array  = "/";
  </script>

An example

  id;first_name;last_name;given_names;is_parent
  integer;string;string;strings;boolean
  1;Dirk;Engel;Dirk,Julius;1
  2;Anna;Engel;Anna,Octovina;1
  3;Bram;Engel;Abraham,Theofilus;0
  4;Paul;Engel;Paulus,Mathijs;

Fetching CSV as Javascript objects

There are two ways to fetch CSV data as objects. Let’s say you want to fetch all the family members from (the relative path) assets/family.csv:

Using String.toObjects()

  <script>
    var members = "assets/family.csv".toObjects();
  </script>

Using Csonv.fetch(url)

  <script>
    var members = Csonv.fetch("assets/family.csv");
  </script>

The resulted objects

When running JSON.stringify(members, null, 2), you will get the following JSON string:

[
  {
    "id": 1,
    "first_name": "Dirk",
    "last_name": "Engel",
    "given_names": [
      "Dirk",
      "Julius"
    ],
    "is_parent": true
  },
  {
    "id": 2,
    "first_name": "Anna",
    "last_name": "Engel",
    "given_names": [
      "Anna",
      "Octovina"
    ],
    "is_parent": true
  },
  {
    "id": 3,
    "first_name": "Bram",
    "last_name": "Engel",
    "given_names": [
      "Abraham",
      "Theofilus"
    ],
    "is_parent": false
  },
  {
    "id": 4,
    "first_name": "Paul",
    "last_name": "Engel",
    "given_names": [
      "Paulus",
      "Mathijs"
    ],
    "is_parent": false
  }
]

Fetching relational data

It is possible to fetch nested relational data with csonv.js. There are two types of relations: 1. has one and 2. has many.

Now let’s say that you have books.csv and authors.csv and you want to get all the books with their authors. Here is what you do:

The data type is specified as follows: <relative path to related CSV file>:<cardinality> of which cardinality can be either 1 or n.

For example:

  id;name;favorite_book;books_read
  integer;string;favorites/books:1;favorites/books:n
  2;Anna Engel;2;1,2,5

books.csv

  id;name;author
  integer;string;authors:1
  1;To Kill an Angry Bird;1
  2;The Rabbit;2
  3;Parslet;3
  4;The Lord of the Things;2
  5;The Michelangelo Code;4

authors.csv

  id;name
  integer;string
  1;Harper Lee
  2;JRR Tolkien
  3;William Shakespeare
  4;Dan Brown

The resulting books.csv data will look like this:

[
  {
    "id": 1,
    "name": "To Kill an Angry Bird",
    "author": {
      "id": 1,
      "name": "Harper Lee"
    }
  },
  {
    "id": 2,
    "name": "The Rabbit",
    "author": {
      "id": 2,
      "name": "JRR Tolkien"
    }
  },
  {
    "id": 3,
    "name": "Parslet",
    "author": {
      "id": 3,
      "name": "William Shakespeare"
    }
  },
  {
    "id": 4,
    "name": "The Lord of the Things",
    "author": {
      "id": 2,
      "name": "JRR Tolkien"
    }
  },
  {
    "id": 5,
    "name": "The Michelangelo Code",
    "author": {
      "id": 4,
      "name": "Dan Brown"
    }
  }
]

Fetching relational data from the opposite direction

As of version 0.1.2 it is possible to fetch relational data of which the foreign keys are defined within the related association. The data type has to be specified as follows: <relative path to related CSV file>:<cardinality>:<inverse type> of which the inverse type is the inverse association that holds the foreign keys. As the foreign keys are defined elsewhere, you can leave column values blank. For instance:

books.csv

  id;name;author
  integer;string;authors:1
  1;To Kill an Angry Bird;1
  2;The Rabbit;2
  3;Parslet;3
  4;The Lord of the Things;2
  5;The Michelangelo Code;4

authors.csv

  id;name;written_books
  integer;string;books:n:author
  1;Harper Lee;
  2;JRR Tolkien;
  3;William Shakespeare;
  4;Dan Brown;

The resulting authors.csv data will look like this:

[
  {
    "id": 1,
    "name": "Harper Lee",
    "written_books": [
      {
        "id": 1,
        "name": "To Kill an Angry Bird"
      }
    ]
  },
  {
    "id": 2,
    "name": "JRR Tolkien",
    "written_books": [
      {
        "id": 2,
        "name": "The Rabbit"
      },
      {
        "id": 4,
        "name": "The Lord of the Things"
      }
    ]
  },
  {
    "id": 3,
    "name": "William Shakespeare",
    "written_books": [
      {
        "id": 3,
        "name": "Parslet"
      }
    ]
  },
  {
    "id": 4,
    "name": "Dan Brown",
    "written_books": [
      {
        "id": 5,
        "name": "The Michelangelo Code"
      }
    ]
  }
]

For a more complex result, please take a look at http://archan937.github.io/csonv.js for a live demo.

Closing words

Well that’s about it! Doesn’t using csonv.js represent simplicity? Have fun! ^^

Contact me

For support, remarks and requests please mail me at [email protected].

Credit

The String.csvSplit() function is based on Ben Nadel’s (@bennadel) blog post:

http://www.bennadel.com / his-blog-post

License

Copyright © 2011 Paul Engel, released under the MIT license

http://holder.nl – http://github.com/archan937 – http://codehero.es – http://gettopup.com – http://twitter.com/archan937 – [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

templayed.js

The fastest and smallest Mustache compliant Javascript templating library written in 2167 bytes (uncompressed)
JavaScript
336
star
2

ruby-mass

Introspect the Ruby Heap by indexing, counting, locating references to and detaching (in order to release) objects - optionally narrowing by namespace
Ruby
246
star
3

jsonv.sh

A Bash command line tool for converting JSON to CSV
Awk
216
star
4

topup

The #1 Javascript Pop Up / Lightbox made by Paul Engel
JavaScript
159
star
5

motion-bundler

Use Ruby gems and mock require statements within RubyMotion applications
Ruby
98
star
6

clickhouse

A Ruby database driver for Clickhouse
JavaScript
89
star
7

stack_tracy

Investigate and detect slow methods within the stack trace of your Ruby (optionally Sinatra) application
Ruby
77
star
8

mecks_unit

A simple Elixir package to elegantly mock module functions within (asynchronous) ExUnit tests using Erlang's :meck library
Elixir
55
star
9

ex_united

Easily spawn Elixir nodes (supervising, Mix configured, easy asserted / refuted) within ExUnit tests
Elixir
43
star
10

rich_cms

Enrichments (e9s) module for a pluggable CMS frontend
Ruby
42
star
11

e9s

Enrichments (e9s) for a pluggable CMS, internationalization (i18n) and localized pluralization
Ruby
40
star
12

jazz_libs

A small gem for rolling out JS libraries (includes repository, demo page and version release rake task)
Ruby
38
star
13

slot_machine

Ruby gem for matching available slots (time slots are also supported)
Ruby
24
star
14

lock-o-motion

Require and mock Ruby gems (including their dependencies) within RubyMotion applications
Ruby
23
star
15

dirty_hashy

Dirty tracking within hashes (with or without indifferent access) or objects as it is expected to be!
Ruby
15
star
16

animate.js

Add slick animations to your web pages and page transitions
JavaScript
14
star
17

raccoon_tip

A lightweight jQuery based balloon tip library
JavaScript
9
star
18

jzip

A Rails gem for Javascript merging and compression using templates (like SASS)
JavaScript
9
star
19

e9s-demo

Rails 3 (and also Rails 2) demo application of the Enrichments (e9s) gem
JavaScript
9
star
20

rich_pluralization

Enrichments (e9s) module for localized pluralization
Ruby
9
star
21

rich_i18n

Enrichments (e9s) module for i18n
Ruby
9
star
22

designer.js

A minimalistic Javascript library to design web pages using absolute positioning
JavaScript
8
star
23

bugs_bunny

A Unicorn served Sinatra demo app which uses Bunny to broadcast AMQP messages to every worker
Ruby
7
star
24

monetdb

A pure Ruby database driver for MonetDB (monetdb5-sql)
Ruby
6
star
25

cached_record

Cache (and optionally memoize) ActiveRecord or DataMapper records in Redis or Memcached
Ruby
5
star
26

seat_holder

The modest Javascript placeholder
JavaScript
4
star
27

unextendable

A small gem making unextending extended module methods within object instances possible
Ruby
4
star
28

relexer.js

A very simple Javascript lexer and parser
JavaScript
4
star
29

oned.js

Trigger callback functions when native HTML or jQuery elements get added to the DOM tree
JavaScript
3
star
30

webhead

An easy-to-use Node web crawler storing cookies, following redirects, traversing pages and submitting forms.
JavaScript
3
star
31

vps

Zero-config deployments of Plug, Phoenix, Rack and Rails apps on a clean Ubuntu server using Docker and Let's Encrypt
Ruby
2
star
32

directiveadmin

A layer on top of ActiveAdmin for adding more power and flexibility (opinionated customizations)
Ruby
2
star
33

rich_support

A small gem making your own gem Rails 2 and 3 compliant and providing the String class a few goodies
Ruby
2
star
34

portcat

Alpine based Docker container with socat installed that can easily map multiple ports to another container
Shell
2
star
35

el.js

A straightforward and lightweight Javascript library for data-binded template rendering
JavaScript
2
star
36

google-apis

A thin layer on top of Google::APIClient for a more intuitive way of working (e.g. with BigQuery or Cloud Storage)
Ruby
2
star
37

directiverecord

A layer on top of ActiveRecord for using paths within queries without thinking about association includes
Ruby
2
star
38

iRacingHUD

Create your own reactive Javascript based UI iRacing HUDs
JavaScript
2
star
39

clustorage

Elixir cluster to store and distribute data and functions by code compilation and hot loading done by a designated "loader node"
Elixir
2
star
40

new_class

Define variable dependent classes without evalling
Ruby
1
star
41

dollar.js

A minimalistic Javascript library for DOM manipulation, template rendering (data binded), event binding, introspection
JavaScript
1
star
42

gem_suit

Test the entire usage workflow (including generators) of your newly generated or existing gem within Rails 2 and 3.
Ruby
1
star