JSON analysis

How to Flatten Nested JSON with SQL: Structs, Lists, and UNNEST

Nested JSON becomes STRUCT and LIST columns in DuckDB. Learn how to reach into structs, turn arrays into rows, and aggregate the flattened result.

Published 2026-05-02·Updated 2026-10-29

Supported JSON shapes

SQL for Files is a good fit for JSON arrays and newline-delimited JSON where each object represents one row. That makes logs, API exports, product catalogs, and event files easier to inspect with SQL.

  • JSON array files such as [{...}, {...}].
  • NDJSON files where each line is one JSON object.
  • Nested arrays or structs that you can inspect and flatten with SQL patterns.

Add JSON data

  1. Open the editor and add your JSON or NDJSON file.
  2. Review the created table in the Database sidebar.
  3. Preview the first rows to confirm field names and inferred types.
  4. Run focused queries before writing larger transformations.

Query top-level fields

When your JSON records have consistent top-level fields, you can query them like columns in a regular table.

SELECT event_type, user_id, created_at
FROM events
WHERE event_type = 'purchase'
ORDER BY created_at DESC
LIMIT 100;

Summarize JSON records

Aggregation works well for event counts, API status codes, product categories, and user activity summaries.

SELECT
  event_type,
  COUNT(*) AS events
FROM events
GROUP BY event_type
ORDER BY events DESC;

Read nested objects with dot notation

When DuckDB reads JSON, nested objects usually become STRUCT columns and arrays become LIST columns. A struct field can be read with dot notation, even several levels deep.

SELECT
  order_id,
  customer.name AS customer_name,
  customer.address.city AS city
FROM orders;

Check the inferred shape first

If the objects in a file have inconsistent shapes, DuckDB may keep a field as JSON text instead of a STRUCT. Run DESCRIBE on the table to see which columns are STRUCT, LIST, or JSON before writing the query.

Turn arrays into rows with UNNEST

Nested JSON often needs one extra step: unnest lists into rows or expand structs into columns. DuckDB includes SQL features for these patterns, and the Learn SQL track includes lessons on UNNEST for nested data.

SELECT
  order_id,
  item.name AS item_name,
  item.quantity
FROM orders,
UNNEST(items) AS item;

Analyze JSON without uploading it

JSON exports can contain logs, customer IDs, analytics events, or sensitive operational data. SQL for Files keeps JSON processing in the browser, so you can inspect files without sending them to a hosted database or converter.

Continue in the editor

Open SQL for Files to add your own CSV, JSON, or Parquet files and try these examples locally in your browser.