PostgreSQL json_populate_record: Usage and Examples
In this article
The json_populate_record function in PostgreSQL converts a JSON object into a structured row based on a predefined composite type or table schema. It maps JSON keys to the column names of the target type; if a key in the JSON matches a column name, the value is inserted into that column. This is primarily used to transform semi-structured JSON data into a strongly typed format for easier querying, inserting into tables, or performing calculations.
What You'll Need
- A PostgreSQL database instance (version 9.4 or higher).
- A defined composite type or an existing table to serve as the target structure.
- A JSON or JSONB object that contains keys corresponding to the target structure's columns.
- Access to a SQL editor or the psql command-line interface.
Step-by-Step
- Define the Target Structure
The function requires a "template" to know which data types to assign to the JSON values. You can use an existing table or create a custom composite type.
Example using a custom type:
CREATE TYPE user_profile AS ( user_id INT, username TEXT, email TEXT, is_active BOOLEAN ); - Prepare Your JSON Data
Ensure your JSON object is formatted as a single object (not an array). The keys must match the names of the fields in your type or table exactly.
Example JSON:
{ "user_id": 101, "username": "jdoe", "email": "jane@example.com", "is_active": true } - Execute the json_populate_record Function
Call the function by passing the target type (cast as the type) and the JSON object.
Basic Syntax:
SELECT * FROM json_populate_record(NULL::user_profile, '{"user_id": 101, "username": "jdoe", "email": "jane@example.com", "is_active": true}');In this command,NULL::user_profiletells PostgreSQL to use theuser_profilestructure but starts with an empty record. - Integrating with Table Data
If you have a table containing JSONB columns and want to expand that JSON into columns for a report, use the function in the
FROMclause or aLATERALjoin. Example:SELECT p.* FROM raw_data_table r, json_populate_record(NULL::user_profile, r.json_column) AS p; - Handling JSONB
If you are using the
JSONBdata type (which is recommended for performance), use the corresponding function:jsonb_populate_record. The syntax and behavior are identical to the JSON version.
Common Mistakes
- Passing a JSON Array: json_populate_record expects a single JSON object. If you pass a JSON array (e.g., ), the function will return an error. To handle arrays, use json_populate_recordset instead.
- Case Sensitivity: PostgreSQL column names are typically lowercase. If your JSON keys are CamelCase (e.g.,
"UserName") but your table columns are lowercase ("username"), the function will not match them and the resulting column will be NULL. - Type Mismatches: If the JSON value cannot be cast to the target column type (e.g., trying to put the string "Hello" into an INTEGER column), PostgreSQL will throw an invalid input syntax error.
- Forgetting the Cast: The first argument must be a record of the target type. Simply passing the name of the type as a string will not work; you must use
NULL::type_name.
Tips
- Use JSONB: Whenever possible, use
jsonb_populate_record. JSONB is stored in a decomposed binary format, making it significantly faster to process than plain JSON. - Partial Objects: You do not need to provide every field in the JSON object. If a key is missing from the JSON, the corresponding column in the resulting record will simply be NULL.
- Combining with INSERT: This function is highly effective for inserting JSON API payloads directly into a table:
INSERT INTO users SELECT * FROM json_populate_record(NULL::users, '{"user_id": 102, "username": "smith"}');
Troubleshooting
If the function is not returning the expected results, try these steps in order:
- Check for NULLs: If the result returns a row but all columns are NULL, verify that the keys in your JSON exactly match the column names of your type/table (including case).
- Validate JSON Syntax: Run the JSON string through a validator or use
SELECT 'your_json'::json;to ensure there are no trailing commas or missing quotes. - Verify Type Definitions: Run
\d type_namein psql to confirm the fields and data types of your composite type match the data you are providing. - Test with a Simple Object: Reduce your JSON to a single key-value pair to isolate whether the issue is a specific data type mismatch or a structural error.
Frequently Asked Questions
What is the difference between json_populate_record and json_populate_recordset?
json_populate_record takes one JSON object and returns one row. json_populate_recordset takes a JSON array of objects and returns multiple rows (a set).
Can I use this function with a table I already created?
Yes. Instead of creating a custom TYPE, you can use the table name as the type. For example: json_populate_record(NULL::my_table_name, json_data).
Does this function modify the original JSON data?
No. It is a read-only transformation function that produces a virtual record based on the input; it does not alter the source data in your tables.
How does it handle nested JSON objects?
It only populates the top level of the record. If a column in your target type is itself another composite type, the function can populate it, but usually, nested JSON is handled by extracting the sub-object first or using a separate population step.
Is there a performance penalty for using this function?
There is a small overhead for the type conversion. For massive datasets, it is faster to use the ->> operator for specific fields, but json_populate_record is much cleaner and more maintainable for large numbers of columns.