The Now Platform® Washington DC release is live. Watch now!
Today we're going to take the things you've already learned, and apply them to something a bit more like the real world. Let's say we've imported that old standby, a .csv file (comma-separated values, with optional quoting of strings containing commas or quotes) — a .csv file with a set of line items on an invoice. Our sample data, from the Dweezle-Dwee Government Surplus Store, looks like this:
dat,qty,itm,amt,ext,cur,typ
10/14/2011,1,"Meat Cleaver, Sharp",47.8,47.8,dollars,purchase
10/12/2011,10,Ballpoint Pen,0.44,4.4,dollars,purchase
7/4/2011,3,"Space Shuttle, Used",-500,-1500,dollars,rma
8/21/2011,1,"Country, ""Greece""",1,1,euros,purchase
9/30/2011,5,"Computer, PC, Obsolete",169.99,849.95,dollars,purchase
var test = 'dat,qty,itm,amt,ext,cur,typ\n';
test += '10/14/2011,1,"Meat Cleaver, Sharp",47.8,47.8,dollars,purchase\n';
test += '10/12/2011,10,Ballpoint Pen,0.44,4.4,dollars,purchase\n';
test += '7/4/2011,3,"Space Shuttle, Used",-500,-1500,dollars,rma\n';
test += '8/21/2011,1,"Country, ""Greece""",1,1,euros,purchase\n';
test += '9/30/2011,5,"Computer, PC, Obsolete",169.99,849.95,dollars,purchase\n';
var result = parse(test);
JSUtil.logObject(result);
function parse(csv) {
var parser = /^(\d+)\/(\d+)\/(\d+),(\d+),((?:"(?:(?:""|[^"])+)")|(?:[^,]+)),(-?[\d.]+),(-?[\d.]+),([^,]+),([^,]+?)$/gm;
var result = [];
var x;
while ((x = parser.exec(csv)) != null) {
var item = {};
item.date = x[3] + '/' + x[1] + '/' + x[2];
item.quantity = x[4] - 0;
item.description = x[5].replace(/^"/, '').replace(/"$/, '').replace(/""/g,'"');
item.amount = x[6] - 0;
item.extended = x[7] - 0;
item.currency = x[8];
item.type = x[9];
result.push(item);
}
return result;
}
Array of 5 elements
[0]: Object
quantity: number = 1
description: string = Meat Cleaver, Sharp
type: string = purchase
amount: number = 47.8
date: string = 2011/10/14
currency: string = dollars
extended: number = 47.8
[1]: Object
quantity: number = 10
description: string = Ballpoint Pen
type: string = purchase
amount: number = 0.44
date: string = 2011/10/12
currency: string = dollars
extended: number = 4.4
[2]: Object
quantity: number = 3
description: string = Space Shuttle, Used
type: string = rma
amount: number = -500
date: string = 2011/7/4
currency: string = dollars
extended: number = -1500
[3]: Object
quantity: number = 1
description: string = Country, "Greece"
type: string = purchase
amount: number = 1
date: string = 2011/8/21
currency: string = euros
extended: number = 1
[4]: Object
quantity: number = 5
description: string = Computer, PC, Obsolete
type: string = purchase
amount: number = 169.99
date: string = 2011/9/30
currency: string = dollars
extended: number = 849.95
item.description = x[5].replace(/^"/, '').replace(/"$/, '').replace(/""/g,'"');
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.