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.
Code
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
Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.
FAQ
- What are the relations in play here?
- `payload` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.