PostgreSQL How to Convert JSON to Table Easily
json_to_recordset or jsonb_to_recordset functions to convert JSON arrays into table rows, for example: SELECT * FROM json_to_recordset('[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]') AS x(id int, name text);Examples
How to Think About It
json_to_recordset or jsonb_to_recordset to turn this list into rows and define the columns by specifying the expected keys and their data types.Algorithm
Code
SELECT * FROM json_to_recordset('[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]') AS x(id int, name text);
Dry Run
Let's trace the JSON array '[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]' through the query.
Input JSON
[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]
Parse JSON to rows
json_to_recordset converts each object to a row with columns id and name.
Output table
Rows: (1, 'Alice'), (2, 'Bob')
| id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
Why This Works
Step 1: json_to_recordset function
The json_to_recordset function takes a JSON array of objects and converts each object into a table row.
Step 2: Defining columns
You must specify the expected columns and their data types after AS so PostgreSQL knows how to map JSON keys to table columns.
Step 3: Query output
The SELECT query returns a table with rows representing each JSON object and columns matching the keys.
Alternative Approaches
SELECT (json_populate_record(NULL::record, elem)).* FROM json_array_elements('[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]'::json) AS elem;SELECT * FROM jsonb_to_recordset('[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]'::jsonb) AS x(id int, name text);
Complexity: O(n) time, O(n) space
Time Complexity
The function processes each JSON object once, so time grows linearly with the number of objects.
Space Complexity
Memory usage grows with the number of rows created from the JSON array.
Which Approach is Fastest?
Using jsonb_to_recordset is generally faster than json_to_recordset if data is stored as jsonb.
| Approach | Time | Space | Best For |
|---|---|---|---|
| json_to_recordset | O(n) | O(n) | Simple JSON arrays stored as json |
| jsonb_to_recordset | O(n) | O(n) | JSON data stored as jsonb, better performance |
| json_array_elements + json_populate_record | O(n) | O(n) | Complex JSON structures, flexible mapping |
AS when using json_to_recordset to avoid errors.AS causes syntax errors.