Expanding JSON Arrays With jsonb_to_recordset

Turn a JSONB array into typed rows with jsonb_to_recordset, then query nested fields and arrays as ordinary relational columns.

SqlData Fetching

Code

snippet
WITH payload AS (
    SELECT '[
        {"id": 1, "name": "ada", "roles": ["admin", "billing"]},
        {"id": 2, "name": "bob", "roles": ["reader"]}
    ]'::jsonb AS doc
)
SELECT
    item.id,
    item.name,
    item.roles,
    array_length(item.roles, 1) AS role_count
FROM payload,
     jsonb_to_recordset(payload.doc) AS item(id int, name text, roles text[])
ORDER BY item.id;

-- roles 在 JSON 里是数组,映射成 text[] 后可直接用 array_length 统计

How the snippet works

At its core this is a single SELECT statement against payload.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; an ORDER BY that fixes the output order.

Using it

Run the statement against the payload table.

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`payload` — referenced directly, no join needed.