CSV
Version compatibility
CSV was introduced in version 4.28.0 of the JourneyApps Container.

Generating a CSV String

Format

main.js
CSV.stringify(source, options);
Parameter
Details
source
One of:
  • Array
  • Matrix (array of arrays)
options (Optional)
Object with the following properties:
  • heading: Array of column headings. Use null to generate a CSV file without a header row.
  • delimiter: Character to separate columns with.
Defaults to ,
Returns: the generated CSV as a string.

Examples

main.js
var mx = [['Cell Phone', 'Black'], ['Computer','Red']];
var csv_file = CSV.stringify(mx, {heading: ['Type', 'Color']});
In this case, csv_file is
csv_file.csv
Type,Color
Cell Phone,Black
Computer,Red
Suppose we have an asset data model object with (amongst others) name and cost as fields, and we want to generate CSV for all assets and their names and costs:
main.js
var allAssets = DB.asset.all().toArray();
var myMx = allAssets.map(function(asset) {
return [asset.name, asset.cost];
});
var csv = CSV.stringify(myMx, {heading: ['Name', 'Cost']});

Parsing a CSV String

Format

CSV.parse(source, options);
Parameter
Details
source
String
options (Optional)
Object with the following properties:
delimiter: Character to separate columns with. If no delimiter is specified, the library detects and uses the appropriate one
Returns: the parsed CSV as an array of arrays.

Example

Assume csv_file's content is:
csv_file.csv
Type,Color
Cell Phone,Black
Computer,Red
main.view.xml
<!-- In the View XML -->
<var name="csv_file" type="attachment" media="text/csv" />
<capture-file bind="csv_file" required="false" />
main.js
var csvFileContent = view.csv_file.toText();
var parsed = CSV.parse(csvFileContent);
// Starting at 1 since the heading is in position 0
for (var i = 1; i < parsed.length; i++) {
var item = parsed[i];
var newAsset = DB.asset.create({
type: item[0],
color: item[1]
});
newAsset.save();
}
Copy link
On this page
Generating a CSV String
Parsing a CSV String