d3 / d3-dsv

A parser and formatter for delimiter-separated values, such as CSV and TSV.

Home Page:https://d3js.org/d3-dsv

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TypeError: Cannot read property 'trim' of undefined

Fil opened this issue · comments

It might happen that CSV files will omit redundant commas, in which case d3.autoType breaks with
TypeError: Cannot read property 'trim' of undefined

This might be a desirable feature, in which case it would be good to trap the error and make it explicit.

However my personal preference would be to have it a bit more fault tolerant and avoid crashing on d3.autoType({ foo: undefined }).

Especially if d3.autoType is made the default for d3.csv (#43).

Bitten by this again…

the simplest fix is to set value = (object[key] || "").trim()
https://github.com/d3/d3-dsv/blob/master/src/autoType.js#L3

but there might be a better way

Hmm. The expectation is that the fields are empty strings, not undefined. We could replace undefined or null with the empty string, but I think this should be considered a bug with how we parse DSV with missing columns: the missing columns should be represented by empty strings, not undefined. You can see the inconsistency with the roundtrip through DSV formatting here.

https://observablehq.com/d/0a81c0d60fb498e7

Probably adding a || "" here:

function objectConverter(columns) {
  return new Function("d", "return {" + columns.map(function(name, i) {
    return JSON.stringify(name) + ": d[" + i + "] || \"\"";
  }).join(",") + "}");
}