Handy angular CSV to JSON pipe

Today, we’re going to talk about a code snippet that can turn CSV data into JSON format using Angular. ๐Ÿค–๐Ÿ’ป

First things first, let’s take a look at the code:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'csvtojson'
})
export class CsvtojsonPipe implements PipeTransform {

  transform(value: string): string {
    if (!value) return "";

    const lines = value.split('\n');
    const header = lines[0].split(',');
    const result = [];

    for (let i = 1; i < lines.length; i++) {
      const obj = {};
      const currentline = lines[i].split(',');

      for (let j = 0; j < header.length; j++) {
        obj[header[j]] = currentline[j] ? currentline[j].trim() : '';
      }

      result.push(obj);
    }

    return JSON.stringify(result);
  }

}

This is a TypeScript class that defines an Angular pipe called CsvtojsonPipe. A pipe is a way to transform data in Angular.

The transform method of the CsvtojsonPipe class is where the magic happens. It takes a string value (presumably a CSV-formatted string) as input and returns a JSON-formatted string.

Here’s what’s happening inside the transform method:

  1. If the input value is falsy, return an empty string. This is just a safeguard in case the input value is undefined, null, or an empty string.
  2. Split the input value into an array of lines using the newline character (\n) as the delimiter.
  3. Extract the header row of the CSV by splitting the first line using commas as the delimiter.
  4. Initialize an empty array called result.
  5. Loop over each line of the CSV (starting from the second line) and create a new object for each line.
  6. Split the current line into an array using commas as the delimiter.
  7. Loop over each element in the header row and add a new key-value pair to the current object. The key is the header element and the value is the corresponding element in the current line. If the value is falsy, set it to an empty string.
  8. Add the current object to the result array.
  9. After all lines have been processed, return the result array as a JSON-formatted string.

You can check out the implementation on a live site here:

https://jcianci12.github.io/converter/

Also here is the pipe to take the JSON and convert it to CSV

So, there you have it! This is a handy code snippet that can turn CSV data into JSON format using Angular. ๐ŸŽ‰ If you’re working with CSV data in your Angular project, you can use this pipe to quickly and easily transform it into a format that’s easier to work with. Happy coding! ๐Ÿ˜Š๐Ÿ‘จโ€๐Ÿ’ป

You can check it out in action here:

https://jcianci12.github.io/converter/

Comments

One response to “Handy angular CSV to JSON pipe”

  1. […] Handy angular CSV to JSON pipe CSV to JSON pipe […]

Leave a Reply

Your email address will not be published. Required fields are marked *