选项
Options
对象描述了使用 csv.parse
函数和 csv.Parser
类解析 CSV 文件时可用的配置。
属性
属性 | 类型 | 描述 |
---|---|---|
delimiter | 字符串 | 用于分隔 CSV 文件中字段的字符。默认为 ',' 。 |
asObjects | 布尔值 | 是否将 CSV 文件的行解析为 JavaScript 对象。如果为 false ,则解析为数组。默认为 false 。 |
skipFirstLine | 布尔值 | 是否跳过 CSV 文件的第一行。默认为 false 。 |
fromLine | (可选)数字 | 开始读取 CSV 文件的行号。默认为 0 。 |
toLine | (可选)数字 | 停止读取 CSV 文件的行号。如果未设置此选项,则读取到文件末尾。 |
asObjects
当 asObjects
设置为 true
时,对 CSV 文件的解析操作将返回一个对象数组。对象键是根据文件第一行推断出的 CSV 文件中的列名,值是 CSV 记录中的字段值。请注意,CSV 文件的第一行会被跳过,因为它被假定包含列名(标题行)。
因此,以下 CSV 文件
name,age
John,30
Jane,25
将被解析为以下对象数组
[
{ "name": "John", "age": "30" },
{ "name": "Jane", "age": "25" }
]
示例
import { open } from 'k6/experimental/fs';
import csv from 'k6/experimental/csv';
const file = await open('data.csv');
const parser = new csv.Parser(file, {
delimiter: ',',
skipFirstLine: true,
fromLine: 2,
toLine: 8,
});
export default async function () {
// The `next` method attempts to read the next row from the CSV file.
//
// It returns an iterator-like object with a `done` property that indicates whether
// there are more rows to read, and a `value` property that contains the row fields
// as an array.
const { done, value } = await parser.next();
if (done) {
throw new Error('No more rows to read');
}
// We expect the `value` property to be an array of strings, where each string is a field
// from the CSV record.
console.log(done, value);
}