/* global File $ */
/* eslint-disable new-cap */
var textlines = [];
var filepath = 'data.csv';
var file = File(File($.fileName).parent.fsName + '/'+ filepath);
if(file.exists) $.writeln('foo');
file.encoding = 'UTF8';
file.lineFeed = 'Macintosh';
file.open('r',undefined,undefined);
var content = file.read();
$.writeln(content);
file.close();
num,name,w,f,h
1,A,1,4,2
2,B,2,3,1
3,C,3,2,4
4,D,4,1,3
5,E,3,2,2
6,F,2,3,1
This scipt asumes that the data.csv
is next to the index.js
. The content of data.csv is:
num | name | w | f | h |
---|---|---|---|---|
1 | A | 1 | 4 | 2 |
2 | B | 2 | 3 | 1 |
3 | C | 3 | 2 | 4 |
4 | D | 4 | 1 | 3 |
5 | E | 3 | 2 | 2 |
6 | F | 2 | 3 | 1 |
This is the quick and dirty approach. For data you don't know how it is formated I suggest using a library like github.com/Rich-Harris/BabyParse. With minor adjustments it works well in ExtendScript.
/* global File $ */
/* eslint-disable new-cap */
// tested on osx
var file = File(File($.fileName).parent.fsName + '/data.csv'); // get the file
file.encoding = 'UTF8'; // set some encoding
file.lineFeed = 'Macintosh'; // set the linefeeds
file.open('r',undefined,undefined); // read the file
var content = file.read(); // get the text in it
file.close(); // close it again
var lines = content.split('\n');// split the lines (windows should be '\r')
var data = [];// will hold the data
var keys = lines[0].split(','); // get the heads
// loop the data
for(var i = 1; i < lines.length;i++){
var obj = {}; // temp object
var cells = lines[i].split(',');// get the cells
// assign them to the heads
obj[keys[0]] = cells[0];
obj[keys[1]] = cells[1];
obj[keys[2]] = cells[2];
obj[keys[3]] = cells[3];
obj[keys[4]] = cells[4];
data.push(obj); // add to data
}
$.writeln(data.toSource()); // show what we got
The output is:
[({num:"1", name:"A", w:"1", f:"4", h:"2"}), ({num:"2", name:"B", w:"2", f:"3", h:"1"}), ({num:"3", name:"C", w:"3", f:"2", h:"4"}), ({num:"4", name:"D", w:"4", f:"1", h:"3"}), ({num:"5", name:"E", w:"3", f:"2", h:"2"}), ({num:"6", name:"F", w:"2", f:"3", h:"1"})]