# JSON to CSV: nested objects, arrays and lost values

> Flatten nested JSON into CSV without dropping or shifting a value: choose a rule for objects and arrays, then count rows and filled cells before and after.

Published 2026-11-26 · https://aiskills402.com/blog/json-to-csv-nested-arrays

To turn nested JSON into CSV without losing or shifting values, decide one rule for each kind of nesting before you write any code, then prove the result with a count. Objects inside objects become dotted column names, arrays become either numbered columns or one joined cell or one row per element, and every record must end up with one shared set of columns in one fixed order. The proof is simple: the number of records in equals the number of rows out, and the number of filled values in equals the number of filled cells out. This JSON to CSV guide shows the rules on a small example and the check that can fail.

## Why JSON to CSV is not a one-to-one copy

A CSV file is a grid. The format document, RFC 4180, asks for one record per line, each line holding an equal count of fields, and admits that no formal specification exists, so programs differ at the edges ([RFC 4180](https://www.rfc-editor.org/rfc/rfc4180)). JSON is a tree. RFC 8259 describes an object as a set of name and value pairs with no order, while an array keeps its order and may hold values of mixed types ([RFC 8259](https://www.rfc-editor.org/rfc/rfc8259)).

Those two sentences explain every problem below. An object has no order, so the column order is something you must choose. An array can be any length, so the number of columns it needs depends on the longest one. A key can be present in one record and absent in the next, so the header cannot be read off the first record alone. Any converter that ignores one of these facts produces a file that looks fine and is wrong.

## A small example

Here are three records. They are deliberately uneven: one has an empty array, one has a key the others lack, one has a null, and one has a zip code with leading zeros that must stay text.

```json
[
  {"id": 1, "name": "Ana", "address": {"town": "Plovdiv", "zip": "4000"}, "tags": ["red", "blue"]},
  {"id": 2, "name": "Boris", "address": {"town": "Varna"}, "tags": []},
  {"id": 3, "name": "Cleo", "address": {"town": "Ruse", "zip": "007"}, "tags": ["green"], "note": null, "vip": true}
]
```

Flattened with dotted names and numbered array columns, the CSV should be this:

```csv
id,name,address.town,address.zip,tags.0,tags.1,note,vip
1,Ana,Plovdiv,4000,red,blue,,
2,Boris,Varna,,,,,
3,Cleo,Ruse,007,green,,,true
```

Look at what happened to each awkward case. The `note` and `vip` columns exist because the third record has those keys, even though the first record does not. Boris has no zip, so that cell is empty, and his empty `tags` array adds nothing. Cleo's `007` is still `007`, and `true` is still lowercase `true`. Every record has eight fields, so every line is equally wide.

## Nested objects: dotted names

The usual rule for a nested object is to join the key names with a dot, so `address` and `town` become `address.town`. Go as deep as the data goes. The trap is a key that already contains a dot: a record with the key `"address.town"` and another with the nested path produce one column name between them, and one value will overwrite the other. A good converter stops and reports that collision instead of picking a winner.

A second trap is a value that is plain text in one record yet an object in another. There is no honest single column for it, so that too deserves an error, not a guess.

## Arrays: three choices, one must be made

An array has no natural place in a grid, so you pick the least bad option for the data you have.

1. **Numbered columns** (`tags.0`, `tags.1`). Nothing is merged, so nothing is lost, but the width grows with the longest array. Use this when arrays are short and the length is bounded.
2. **One cell with a separator** (`red|blue`). The table stays narrow. It only works if the separator never occurs inside an element; otherwise two elements merge into one and you cannot tell afterwards.
3. **One row per element.** Each array element gets its own row, with the parent's other columns repeated. This is the right shape for a list of line items, but it changes the row count, so your check must count differently, as explained below.

Whichever you choose, write it down next to the file. A reader who finds `tags.1` empty has to know whether that means no second tag or a lost one.

## Values that quietly change

Most losses do not come from structure. They come from the value being rewritten on its way through. Copy each JSON value as its text, and watch for these:

- **Numbers.** `1.10` is a different token from `1.1`, and a tool that parses to a float and prints it back drops the zero. Large integers and exponents suffer the same way.
- **Leading zeros.** A zip code or an account number such as `007` is a string. A spreadsheet that opens the file may turn it into the number seven, so keep it as text in the file and import the column as text.
- **Booleans.** Keep `true` and `false` as they were written; some tools upper-case them.
- **Null versus absent.** In CSV a null and an absent key both become an empty cell. That is a real loss of information, so if the difference matters, add a marker column or keep the original JSON.
- **Commas, quotes and line breaks inside values.** [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180) puts such fields in double quotes and doubles any quote inside them. A value like `He said "hi", twice` must come out as `"He said ""hi"", twice"`.
- **Unicode and the line ending.** The standard's line break is CRLF; many parsers accept a bare line feed, but a value that itself holds a line break must stay inside quotes.

Duplicate keys deserve a special mention. [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259) says the names in an object SHOULD be unique, and cautions that a repeated key makes software behave unpredictably. Many parsers keep only the last value, so the first one vanishes before your converter ever sees it. We measured how a repeated key goes missing when a model does the conversion, in [a report on silent data loss](https://aiskills402.com/blog/llm-csv-json-conversion-loses-data).

## A check that can fail

Write the check before you trust the output, and make sure it can say no.

1. Count the records in the JSON array. Count the data rows in the CSV, with a real CSV parser, not by counting newlines, because a quoted cell can contain a line break. For the flat and numbered-column choices the two counts must match. For one row per element, the CSV count must equal the sum of the array lengths, with an empty array counting as one row.
2. Count the filled leaf values in the JSON: every string, number and boolean, and not nulls or empty arrays. Count the non-empty cells in the CSV. For the example above both counts are fifteen.
3. Compare a few cells by key, not by position: take a record by its `id`, read `address.zip` from the JSON and from the CSV, and require the same text.
4. Make it fail on purpose. Delete one value from the CSV, or shift one cell by one column, and run the check again. If the counts still match, the check is measuring the wrong thing.

Here is a short script that does steps one and two for the flat, numbered-column choice. Save it as `check.mjs` and run it with `node check.mjs data.json out.csv`. It uses a small parser that understands quotes; swap in your favourite CSV library if you have one.

```js
import { readFileSync } from "node:fs";

const data = JSON.parse(readFileSync(process.argv[2], "utf8"));

function leaves(v) {
  if (Array.isArray(v)) return v.reduce((n, x) => n + leaves(x), 0);
  if (v && typeof v === "object") return Object.values(v).reduce((n, x) => n + leaves(x), 0);
  return v === null ? 0 : 1;
}

function parseCsv(text) {
  const rows = [[""]];
  let q = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i], r = rows[rows.length - 1];
    if (q) {
      if (c === '"' && text[i + 1] === '"') { r[r.length - 1] += '"'; i++; }
      else if (c === '"') q = false;
      else r[r.length - 1] += c;
    } else if (c === '"') q = true;
    else if (c === ",") r.push("");
    else if (c === "\n") rows.push([""]);
    else if (c !== "\r") r[r.length - 1] += c;
  }
  if (rows[rows.length - 1].every((x) => x === "")) rows.pop();
  return rows;
}

const rows = parseCsv(readFileSync(process.argv[3], "utf8"));
const body = rows.slice(1);
const filled = body.reduce((n, r) => n + r.filter((x) => x !== "").length, 0);
const width = rows[0].length;
const values = data.reduce((n, r) => n + leaves(r), 0);

console.log("records", data.length, "rows", body.length);
console.log("values", values, "cells", filled);
console.log("ragged lines", body.filter((r) => r.length !== width).length);
process.exitCode =
  data.length === body.length && values === filled && body.every((r) => r.length === width) ? 0 : 1;
```

The third line of output matters too. [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180) wants equal width on every line, so a ragged line means a quote went wrong upstream and the columns to its right are shifted.

## Before you open the file in a spreadsheet

If any value can come from outside, a user's name or a comment for example, look at the first character of each cell. OWASP describes CSV injection: a cell that begins with an equals sign, plus, minus or at sign may be read as a formula when the file is opened in a spreadsheet program, and the same page lists tab and line breaks as risky starts too ([OWASP CSV Injection](https://owasp.org/www-community/attacks/CSV_Injection)). OWASP also warns that a spreadsheet may strip the quotes or escape characters when the file is saved and opened again, so a fix that looked safe can stop working. This is a different problem from lost values, but it sits at the same stage, and a faithful copy of a hostile value is still a faithful copy. Decide whether the file is for a program or for a person, and prefix or reject such cells if it is for a person.

Where the CSV goes into another program, not a spreadsheet, you usually want the opposite: the exact text, untouched. Keep both needs in mind and name which one the file serves.

## Going back, and when the file arrives broken

A flat CSV can be turned back into JSON, but only if you know the column naming rule. Dotted names and numbered columns are a convention, and the reader has to rebuild the nesting from them. Keep every value as a string unless a column is declared as a number; guessing types is the same loss in the other direction. If the CSV you received does not parse at all, repair it first, then convert, and do the same count on the repaired file. Whether plain code or a model is the better tool for that repair is argued from measurements in [a separate post on repairing data](https://aiskills402.com/blog/data-repair-code-vs-llm), which is worth reading before you automate it.

## Our skills for this topic

- [JSON flattening skill](/skills/json-to-csv-flatten): turns a list of JSON records into one CSV table, using dotted names, numbered array columns or joined cells, and gives a one-line refusal when two keys collide or a value changes type between records.
- [CSV to JSON skill](/skills/csv-to-json-rows): reads CSV into one JSON object per row, keeps each cell as the text it shows, and refuses on short rows, repeated headers and open quotes.
- [CSV repair skill](/skills/csv-repair): fixes CSV that does not parse, such as unclosed quotes, stray delimiters and short rows, without touching cell text, and refuses when a fix would push data into another column.
- [JSON repair skill](/skills/json-repair): a neighbouring job, for broken or truncated JSON.
- [JSON Lines repair skill](/skills/jsonl-repair): the same neighbouring job for JSON Lines files.
- [HTML table to CSV skill](/skills/html-table-to-csv): for tables scraped from a page.

## When this does not apply

These rules are for a list of records that share a rough shape. JSON that is a deeply irregular tree, such as a document with arbitrary nesting, has no good flat form; keep it as JSON or load it into a database that stores JSON. The counting check also has blind spots: it will not notice two values swapped between columns of the same row, or a number that lost a trailing zero, which is why step three compares real cells by key. A null and an absent key look identical in the file, so the count cannot tell them apart. The script above is a sketch for the flat choice, was run only on the example in this guide, and does not cover one row per element. The three public documents were read on 26 November 2026 and could have changed since.
