Home › Blog

Nested JSON to Excel: how objects and arrays become columns

A worksheet is a grid, while JSON can nest objects inside objects and lists inside both. Any JSON to Excel conversion has to decide what to do with that nesting. Here are the usual options and what each one costs.

What goes wrong without flattening

SheetJS, the library most JavaScript tools use to write Excel files, maps each key of an object to a column. When a value is itself an object or an array, it cannot put it in a cell. With SheetJS 0.20.3 this record:

{ "id": 1, "shipping": { "city": "Berlin" }, "items": ["k", "m"] }

gives a sheet with the headers id, shipping and items, and the last two cells empty. No error, just missing data. That is why the JSON to Excel converter on this site flattens every record before it hands it to SheetJS.

Nested objects: dotted column names

An object inside a record has a fixed set of keys, so each key can become a column. The path is joined with dots:

{ "order": 1001, "shipping": { "city": "Berlin", "country": "DE" } }

order | shipping.city | shipping.country
1001  | Berlin        | DE

This works at any depth: {"a": {"b": {"c": 1}}} becomes a column a.b.c. It is also what pandas.json_normalize does in Python by default, so dotted headers are a common convention.

Arrays: one cell, or one row per item

Arrays are harder because their length changes from record to record. There are two reasonable layouts.

Keep the array in one cell

The converter writes the array as JSON text, so ["keyboard","mouse"] sits in the items cell. You keep one row per record and lose nothing, but you cannot filter on a single item in Excel.

One row per array item

Repeat the parent fields on every row, once per item. Power Query's Expand to New Rows does this in Excel. In JavaScript you can do it before converting:

const rows = orders.flatMap(({ items, ...order }) =>
  items.length ? items.map((item) => ({ ...order, item })) : [{ ...order, item: null }]
);

With the sample orders this turns 3 orders into 4 rows: two for order 1001, one each for 1002 and 1003. The empty-array case keeps order 1003 with an empty item instead of dropping it. Keep in mind that totals now repeat, so summing the total column counts order 1001 twice.

Two sheets

For larger data, a third layout is a sheet of orders and a separate sheet of items that carries the order number, like two database tables. Sums stay correct, and you join them with XLOOKUP when you need both.

Getting nested JSON back from Excel

Dotted headers and JSON text cells can be reversed. The Excel to JSON converter has an option that turns shipping.city back into {"shipping": {"city": ...}} and parses cells that hold JSON arrays or objects. A file made by the JSON to Excel converter comes back with the same structure, as long as nobody renamed the headers.