TECH

Convert CSV, TSV, PSV files to JSON in Typescript

Easily convert CSV, TSV, PSV, or any other delimiter file to JSON with this single piece of code written in typescript.

Hitesh Verma Jul 4, 2023 · 1 min. read
Photo by <a href="https://unsplash.com/@ricaros" target="_blank">Danial Igdery</a> on <a href="https://unsplash.com" target="_blank">Unsplash</a>
Photo by Danial Igdery on Unsplash

Easily convert CSV, TSV, PSV, or any other delimiter file to JSON with this single piece of code written in typescript.

import fs = require("fs/promises");

export class Converter {
  /**
   * Convert text file to JSON
   */
  async textToJson(filePath: string, delimiter = "|") {
    const data = (await fs.readFile(filePath)).toString().split("\n");
    const headers = data.shift()!.split(delimiter);
    const jsonArr = [];

    for (let i = 0; i < data.length; i++) {
      if (/^\s*$/.test(data[i])) continue; // skip empty lines

      const values = data[i].split(delimiter);
      const json: any = {};

      for (let i = 0; i < values.length; i++) {
        const key = headers[i].trim().replace(/ /g, "_");
        json[key] = values[i].trim();
      }

      jsonArr.push(json);
    }

    let jsonStr = "[";

    for (let i = 0; i < jsonArr.length; i++) {
      jsonStr += JSON.stringify(jsonArr[i]);
      if (i !== jsonArr.length - 1) jsonStr += ",";
    }

    jsonStr += "]";
    return JSON.parse(jsonStr) as any[];
  }
}
Read next

Customized Calendar in Flutter

Hey, have you ever wanted a date-picker in your app but not in a dialog box? And you tried all the dart packages out there but cannot change their UIs

Hitesh Verma May 28, 2023 · 9 min read

Flutter: Custom Cupertino Date Picker

Hitesh Verma in TECH
May 28, 2023 · 6 min read

Flutter | Highlight searched text in results

Hitesh Verma in TECH
May 12, 2023 · 4 min read