Examples of advanced parsing
Example 1: Tab-separated values or TDF
This scenario shows processing a file generated as tab-separated values.
Script:
var tsvData = "Name\tAge\tCity\nJohn\t30\tNew York";
var options = {
format: "TDF",
header: true // Treat first row as headers
};
var records = csvutils.parseWithOptions(tsvData, options);
processlog.info(records[0]["City"]); // Output: New York
Example 2: Custom delimiter (|) without headers
This scenario shows processing a raw data that uses pipes (|) to separate values and has no header record.
Input data:
Plaintext ItemA|500|In Stock ItemB|20|Out of Stock
Script:
var rawData = "ItemA|500|In Stock\nItemB|20|Out of Stock";
var options = {
delimiter: "|",
header: false // Default, but explicit for clarity
};
var rows = csvutils.parseWithOptions(rawData, options);
// Since there are no headers, we access by index [0], [1], etc.
var firstItem = rows[0];
processlog.info("Product: " + firstItem[0]); // Output: Product: ItemA
processlog.info("Price: " + firstItem[1]); // Output: Price: 500
Example 3: Manually specifying headers
This scenario shows processing of a file that contains data with no header row, but you must map them to names for easier coding.
Input data:
Code snippet apple,red,sweet lemon,yellow,sour
Script:
var fruitData = "apple,red,sweet\nlemon,yellow,sour";
var options = {
header: true, // Tell parser to map to the headers provided below
headers: ["Fruit", "Color", "Taste"]
};
var records = csvutils.parseWithOptions(fruitData, options);
processlog.info(records[1]["Fruit"]); // Output: lemon
processlog.info(records[1]["Taste"]); // Output: sour