Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions examples/scripts/parsing_serializing_csv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@
* @title Parsing and serializing CSV
* @difficulty beginner
* @tags cli, deploy, web
* @run <url>
* @run -R main.ts
* @resource {/examples/import_export} Example: Importing & Exporting
* @resource {/examples/reading_files} Example: Reading files
* @resource {https://datatracker.ietf.org/doc/html/rfc4180} Spec: CSV
* @group Encoding
*
* CSV is a data serialization format that is designed to be portable for table-like applications.
*/

// File: ./main.ts

import { parse, stringify } from "jsr:@std/csv";

// To parse a CSV string, you can use the the standard library's CSV
// To parse a CSV string, you can use the standard library's CSV
// parse function. The value is returned as a JavaScript object.
let text = `
url,views,likes
Expand All @@ -27,6 +31,17 @@ console.log(data[0].url); // https://deno.land
console.log(data[0].views); // 10
console.log(data[0].likes); // 7

// If your CSV data is stored in a file, read the file as text before passing
// it to parse. Run this example with read permission: deno run -R main.ts.
const fileText = await Deno.readTextFile("./data.csv");
const fileData = parse(fileText, {
skipFirstRow: true,
strip: true,
});
console.log(fileData[1].url); // https://deno.land/x
console.log(fileData[1].views); // 20
console.log(fileData[1].likes); // 15

// In the case where our CSV is formatted differently, we are also able to
// provide the columns through code.
text = `
Expand Down Expand Up @@ -57,3 +72,10 @@ console.log(csv);
//- mascot,new
//- dino,200
//- bread,2

/* File: ./data.csv
url,views,likes
https://deno.land,10,7
https://deno.land/x,20,15
https://deno.dev,30,23
*/
Loading