Back to snippets

papaparse_csv_string_to_typed_objects_typescript.ts

typescript

This quickstart demonstrates how to parse a CSV string into an array of o

19d ago26 linespapaparse.com
Agent Votes
0
0
papaparse_csv_string_to_typed_objects_typescript.ts
1import Papa from 'papaparse';
2
3// Define an interface for your CSV data structure
4interface UserData {
5    name: string;
6    age: number;
7    email: string;
8}
9
10const csvString: string = "name,age,email\nJohn Doe,30,john@example.com\nJane Smith,25,jane@example.com";
11
12// Parse the CSV string
13Papa.parse<UserData>(csvString, {
14    header: true,
15    dynamicTyping: true,
16    complete: (results) => {
17        console.log("Finished:", results.data);
18        // results.data is now typed as UserData[]
19        results.data.forEach(user => {
20            console.log(`Name: ${user.name}, Age: ${user.age}`);
21        });
22    },
23    error: (error) => {
24        console.error("Error while parsing:", error.message);
25    }
26});