denoland / deno_std

The Deno Standard Library
https://jsr.io/@std
MIT License
2.83k stars 581 forks source link

CSV - option to automatically infer headers #3857

Open sergeysolovev opened 7 months ago

sergeysolovev commented 7 months ago

It would be amazing if this code worked, probably by passing something like inferHeaders option (suggested by @crowlKats).

import { stringify } from 'https://deno.land/std@0.208.0/csv/mod.ts';
const arr = [{ a: 1, b: 2 }, { a: 3, b: 4 }];
console.log(stringify(arr));
sigmaSd commented 3 months ago

just want to mention that this works if you pass the columns options

console.log(stringify(arr, { columns: ["a", "b"] }));

without it it errors with

error: Uncaught (in promise) StringifyError: No property accessor function was provided for object
      throw new StringifyError(
sergeysolovev commented 3 months ago

@sigmaSd thank you for the suggestion! It helped me to simplify my little wrapper to auto-stringify an array of objects

export class Csv {
  static stringify(array: Record<string, unknown>[]) {
    const columns = Object.keys(array[0]);
    return stringify(array, { columns }).trim();
  }
}
iuioiua commented 3 months ago

I like this idea! Thoughts, @kt3k?

sigmaSd commented 3 months ago

In the mean while, shouldn't columns property be mandatory instead of optional ? because currently it feels weird that if you just use stringify(data) it throws

timreichen commented 3 months ago

Related: https://github.com/denoland/deno_std/issues/2660

iuioiua commented 3 months ago

Closing as duplicate of #2660.

dandv commented 1 month ago

@iuioiua This is a feature request for auto-inferring headers, the way mature CSV libraries do.

2660 is an issue about marking the columns option as mandatory. If this feature (#3857) is implemented, then #2660 can be closed. Until then, #2660 can be resolved independently. We should reopen this issue (#3857).

@sergeysolovev: can you please rename this issue to "CSV - option to automatically infer headers" or something similar?

sergeysolovev commented 1 month ago

@dandv alright, ready