You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript(TS)中将CSV格式文本文件转换为JSON格式

TypeScript实现CSV转目标JSON数组方案

实现思路

  • 拆分CSV文本为行数组,过滤掉首尾空行
  • 提取第一行作为表头,拆分得到字段名列表
  • 遍历后续每一行数据,拆分字段后和表头一一映射,其中id字段手动转换为数字类型
  • 所有映射后的对象组合为数组,可直接使用JSON.stringify输出格式化的JSON

完整TS实现代码

// 定义返回数据的类型,确保类型安全
interface CsvRecord {
  id: number;
  code: string;
  name: string;
}

function csvToJson(csvContent: string): CsvRecord[] {
  // 按换行拆分,同时去掉每行首尾空格,过滤空行
  const lines = csvContent.split('\n')
    .map(line => line.trim())
    .filter(line => line.length > 0);

  // 拆分表头得到字段名
  const headers = lines[0].split(',').map(header => header.trim());

  // 处理每一行数据
  const result: CsvRecord[] = [];
  for (let i = 1; i < lines.length; i++) {
    const values = lines[i].split(',').map(val => val.trim());
    const record: Record<string, any> = {};
    headers.forEach((header, index) => {
      record[header] = values[index];
    });
    // id转换为数字类型
    result.push({
      id: Number(record.id),
      code: record.code,
      name: record.name
    });
  }

  return result;
}

// 测试用例
const testCsv = `id,code,name
1,PRT,Print
2,RFSH,Refresh
3,DEL,Delete `;

const jsonArray = csvToJson(testCsv);
// 输出格式化的JSON字符串,缩进2空格
console.log(JSON.stringify(jsonArray, null, 2));

注意:上述代码仅适配无特殊转义符的简单CSV格式,如果需要处理字段包含引号、转义逗号等复杂场景,可引入成熟的第三方CSV解析库降低开发成本。

运行输出

执行后得到的结果和要求的格式完全一致:

[
  {
    "id": 1,
    "code": "PRT",
    "name": "Print"
  },
  {
    "id": 2,
    "code": "RFSH",
    "name": "Refresh"
  },
  {
    "id": 3,
    "code": "DEL",
    "name": "Delete"
  }
]

内容的提问来源于stack exchange,提问作者Rafael Segura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 16:15:03