DEV Community

Dev Nestio
Dev Nestio

Posted on

JSON ↔ CSV Converter with Nested Object Flattening

Converting between JSON and CSV sounds simple until nested objects appear. I built a browser-only converter that handles them.

Try it: https://devnestio.pages.dev/json-to-csv/

Flattening nested objects

function flattenObj(obj, prefix) {
  const out = {};
  for (const [k, v] of Object.entries(obj)) {
    const key = prefix ? prefix + "." + k : k;
    if (v !== null && typeof v === "object" && !Array.isArray(v)) {
      Object.assign(out, flattenObj(v, key));
    } else {
      out[key] = v === null ? "" : Array.isArray(v) ? JSON.stringify(v) : String(v);
    }
  }
  return out;
}
Enter fullscreen mode Exit fullscreen mode

Nested {address: {city: "Tokyo"}} becomes address.city column.

CSV field quoting

function escapeCsvField(val, delim, q) {
  if (!q) return val;
  const needsQuote = val.includes(delim) || val.includes(q) || val.includes("\n");
  if (!needsQuote) return val;
  return q + val.replace(new RegExp(q, "g"), q + q) + q;
}
Enter fullscreen mode Exit fullscreen mode

Features

  • JSON → CSV and CSV → JSON both directions
  • Comma, semicolon, tab, pipe delimiters
  • Single/double/no quoting
  • BOM prefix for Excel compatibility
  • Optional header row
  • Preview table (first 10 rows)
  • Download as .csv or .json

DevNestio — browser-only developer tools.

Top comments (0)