Quantcast
Channel: UselessCode.org Blog
Viewing all articles
Browse latest Browse all 27

Introducing UCSV

$
0
0

Background

UCSV is a small (less than 1kb when minified and gzipped) JavaScript library. It provides a simple interface for importing and exporting CSV data into and out of JavaScript applications. UCSV namespaces all of it’s functions in a global variable named CSV. It has two easy to use methods: csvToArray and arrayToCsv. Below are a few simple examples demonstrating how to use UCSV.

In these examples we’ll use a couple of small data sets of unemployment statistics from January 2010:

Data set 1

Alaska,8.5
Arkansas,7.6
California,12.5

Data set 2

Utah,6.8
Virginia,6.9
Washington,9.3

Converting CSV into a JavaScript Array

After our first data set is converted to a JavaScript string it looks like this:

"Alaska,8.5\nArkansas,7.6\nCalifornia,12.5\n"

The following code will take this CSV data and convert it into an array. Each item represents a row of data and itself is an array representing each field in the row.

var arr,
data = "Alaska,8.5\nArkansas,7.6\nCalifornia,12.5\n"
 
arr = CSV.csvToArray(data);
console.log(arr);
/* arr now contains the array:
[
["Alaska", "8.5"],
["Arkansas", "7.6"],
["California", "12.5"]
]
*/

By default UCSV complies to RFC 4180 and does not trim leading or trailing space in fields. If you would like this behavior you can set the optional second parameter to True.

var arr,
// padding added to fields
data = "  Alaska  ,8.5\n Arkansas ,7.6\nCalifornia  ,  12.5\n"
 
// setting the second parameter to true will strip
// the padding when importing
arr = CSV.csvToArray(data, true);
 
/* arr now contains the array:
[
["Alaska", "8.5"],
["Arkansas", "7.6"],
["California", "12.5"]
]
*/

Converting an Array Into a CSV

If we write our second data set as an array it ends up looking like this:

[
["Utah",6.8],
["Virginia",6.9],
["Washington",9.3]
]

We can convert it into a string using the following JavaScript:

var data,
arr = [
["Utah",6.8],
["Virginia",6.9],
["Washington",9.3]
];
 
data = CSV.arrayToCsv(arr);
 
/* data now contains: "Utah,6.8\nVirginia,6.9\nWashington,9.3" */

Conclusion

That’s all there is to using UCSV. If you would like to learn more about UCSV you can find a more complex demo, documentation and source code at the UCSV project homepage.


Viewing all articles
Browse latest Browse all 27

Trending Articles