PostgreSQL json_to_record: How to Convert JSON to Rows
In this article
The json_to_record function in PostgreSQL transforms a single JSON object into a structured record (a row) with specific columns and data types. This allows you to treat JSON keys as table columns, enabling you to use standard SQL filters, joins, and aggregations on semi-structured data. To use it, you must provide the JSON object and a column definition list that matches the keys you wish to extract.
What You'll Need
- A PostgreSQL database (version 9.4 or newer).
- A table containing
jsonorjsonbdata, or a raw JSON string to test with. - Basic knowledge of SQL
SELECTstatements and data types (e.g.,TEXT,INTEGER,BOOLEAN).
Step-by-Step
- Identify your JSON structure
Before writing the query, examine the JSON object you want to convert. Note the exact keys and the types of values they hold. For example, if your JSON is
{"id": 101, "name": "Widget", "active": true}, you have an integer, a string, and a boolean. - Define the target schema
The
json_to_recordfunction requires anASclause. This clause defines the column names and data types that PostgreSQL should create for the resulting record. These names must match the keys in your JSON object exactly.
Example schema:AS (id INT, name TEXT, active BOOLEAN) - Implement the function in the FROM clause
Unlike standard functions that return a single value,
json_to_recordreturns a record. Therefore, it must be placed in theFROMclause of your query. This treats the function output as if it were a virtual table.
Basic Syntax:
SELECT * FROM json_to_record('{"id": 101, "name": "Widget", "active": true}') AS x(id INT, name TEXT, active BOOLEAN); - Apply the function to a table column
To convert JSON stored in a table, use a
CROSS JOIN LATERAL. This allows the function to reference a column from the preceding table in theFROMclause for every row.
Example:
SELECT t.id, j.name, j.active FROM my_table t, json_to_record(t.json_column) AS j(name TEXT, active BOOLEAN); - Filter and manipulate the resulting columns
Now that the JSON is converted to a record, you can use a
WHEREclause to filter based on the newly created columns, just as you would with a standard table.
Example:
SELECT j.name FROM my_table t, json_to_record(t.json_column) AS j(name TEXT, active BOOLEAN) WHERE j.active = true;
Common Mistakes
- Mismatching Key Names: If the column name in the
ASclause does not match the key in the JSON object exactly (including case sensitivity), PostgreSQL will return aNULLvalue for that column rather than throwing an error. - Incorrect Data Types: Providing a data type that is incompatible with the JSON value (e.g., trying to cast a string "Hello" to an
INTEGER) will result in a runtime error. - Using it in the SELECT list: Attempting to use
json_to_recorddirectly in theSELECTlist (e.g.,SELECT json_to_record(...) FROM table) will fail because the function returns a record type, not a scalar value. It must be in theFROMclause. - Confusing it with json_populate_record:
json_to_recordallows you to define the columns on the fly.json_populate_recordrequires an existing table or composite type to define the structure.
Tips
- Use jsonb_to_record for Performance: If your data is stored as
jsonb(binary JSON), usejsonb_to_recordinstead. It is generally faster and more efficient for processing. - Combine with json_array_elements: If you have a JSON array of objects, use
json_array_elementsfirst to expand the array into individual rows, then usejson_to_recordto turn those objects into columns. - Alias your records: Always provide a clear alias (like
AS jorAS data) for the record. This makes yourSELECTlist much more readable when joining multiple tables.
Troubleshooting
If your query is not returning the expected results, try these steps in order:
- Check for NULLs: If columns are coming back as
NULL, verify the case sensitivity of your JSON keys. JSON keys are case-sensitive;"Name"is not the same as"name". - Validate JSON Format: Ensure the input is a valid JSON object (surrounded by curly braces
{}). If the input is a JSON array (surrounded by square brackets[]),json_to_recordwill fail. Usejson_array_elementsfirst. - Verify Data Types: If you receive a "type mismatch" error, check the values in your JSON. Ensure that numeric fields don't contain unexpected strings or empty quotes that cannot be cast to integers.
- Test with a Static String: Replace your table column with a hardcoded JSON string (e.g.,
'{"a": 1}') to determine if the issue lies with the function syntax or the data stored in your table.
Frequently Asked Questions
What is the difference between json_to_record and json_to_recordset?
json_to_record converts a single JSON object into one row. json_to_recordset converts a JSON array of objects into multiple rows.
Can I use this function with the JSONB data type?
Yes, but you should use the corresponding jsonb_to_record function for better performance and compatibility with jsonb columns.
Do I have to define every single key in the JSON object?
No. You only need to define the keys you actually want to extract. Any keys present in the JSON object that are not listed in the AS clause will be ignored.
Is json_to_record faster than using the ->> operator?
For extracting a single value, the ->> operator is faster. However, when extracting many fields from the same object, json_to_record is often more readable and can be more efficient as it parses the object once for all defined columns.
Can I use this function in a View?
Yes. You can create a standard SQL View that uses json_to_record in the FROM clause. This is a common way to present semi-structured JSON data as a traditional relational table to end-users or BI tools.