Recursive CTE Flattens Nested JSON
A recursive CTE walks nested jsonb children with jsonb_array_elements, tracking depth and path until every leaf array runs out.
Code
WITH RECURSIVE walk AS (
SELECT
node.value->>'name' AS name,
node.value->'children' AS children,
0 AS depth,
node.value->>'name' AS path
FROM jsonb_array_elements('[
{"name": "root", "children": [
{"name": "team-a", "children": [{"name": "dev", "children": []}]},
{"name": "team-b", "children": []}
]}
]'::jsonb) AS node(value)
UNION ALL
SELECT
c.node->>'name',
c.node->'children',
w.depth + 1,
w.path || '/' || (c.node->>'name')
FROM walk w
CROSS JOIN LATERAL jsonb_array_elements(w.children) AS c(node)
WHERE jsonb_typeof(w.children) = 'array'
)
SELECT name, depth, path
FROM walk
ORDER BY path;How this file behaves — Recursive CTE Flattens Nested JSON
The statement is SELECT, reading the recursive CTE walk. There is no base table: the anchor member turns one inline jsonb literal into rows with the set-returning function jsonb_array_elements, and the recursive member reaches back into walk through CROSS JOIN LATERAL.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; one CROSS JOIN LATERAL pairing each walk row with the rows the set-returning function produces; a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; a UNION stitching together the result sets of separate queries.
Using it
Run the final SELECT against the CTE walk — the outer query reads walk directly; the jsonb literal is consumed inside the CTE.
Interactive Tools for This Topic
FAQ
- Which objects does the SQL touch?
- `jsonb_array_elements`, `walk`, `lateral`, combined through a join.
Report a problem with this exampleOpens a pre-filled issue on GitHub.