-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathparsing_serializing_csv.ts
59 lines (56 loc) · 1.56 KB
/
parsing_serializing_csv.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* @title Parsing and serializing CSV
* @difficulty beginner
* @tags cli, deploy, web
* @run <url>
* @resource {/examples/import_export} Example: Importing & Exporting
* @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.
*/
import { parse, stringify } from "jsr:@std/csv";
// To parse a CSV string, you can use the the standard library's CSV
// parse function. The value is returned as a JavaScript object.
let text = `
url,views,likes
https://deno.land,10,7
https://deno.land/x,20,15
https://deno.dev,30,23
`;
let data = parse(text, {
skipFirstRow: true,
strip: true,
});
console.log(data[0].url); // https://deno.land
console.log(data[0].views); // 10
console.log(data[0].likes); // 7
// In the case where our CSV is formatted differently, we are also able to
// provide the columns through code.
text = `
https://deno.land,10,7
https://deno.land/x,20,15
https://deno.dev,30,23
`;
data = parse(text, {
columns: ["url", "views", "likes"],
});
console.log(data[0].url); // https://deno.land
console.log(data[0].views); // 10
console.log(data[0].likes); // 7
// To turn a list of JavaScript object into a CSV string, you can use the
// standard library's CSV stringify function.
const obj = [
{ mascot: "dino", fans: { old: 100, new: 200 } },
{ mascot: "bread", fans: { old: 5, new: 2 } },
];
const csv = stringify(obj, {
columns: [
"mascot",
["fans", "new"],
],
});
console.log(csv);
//- mascot,new
//- dino,200
//- bread,2