Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL jsonb_populate_record Guide and Examples

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The jsonb_populate_record function in PostgreSQL converts a JSONB object into a structured record based on a predefined table or composite type. It maps JSON keys to column names; if a key matches a column name, the value is inserted into that column. This is primarily used to transform unstructured JSON data into a relational format for easier filtering, joining, and reporting without manually extracting every field using the ->> operator.

What You'll Need

  • A PostgreSQL database (version 9.4 or later, as JSONB was introduced then).
  • An existing table or a defined composite type to serve as the "template" for the record.
  • Data stored in a JSONB column or a JSONB literal.

Step-by-Step

  1. Define the Target Structure: Create a table or a type that represents the structure you want the JSON data to fit into. The column names in this table must match the keys in your JSONB object.
    CREATE TABLE user_profile (
                first_name TEXT,
                last_name TEXT,
                age INTEGER,
                is_active BOOLEAN
            );
  2. Prepare your JSONB Data: Ensure your data is in JSONB format. If you have a JSON column, cast it using ::jsonb.
    -- Example JSONB literal
            '{"first_name": "Jane", "last_name": "Doe", "age": 30, "is_active": true}'::jsonb
  3. Execute the Populate Function: Use jsonb_populate_record by passing the target table (or a record from that table) and the JSONB object. To use a table as the template, you typically pass a NULL record of that table's type.
    SELECT jsonb_populate_record(NULL::user_profile, '{"first_name": "Jane", "last_name": "Doe", "age": 30, "is_active": true}'::jsonb);
  4. Integrate with Table Data: If you have a table containing a JSONB column and you want to expand that column into the structure of another table, use the function in the SELECT clause.
    SELECT (jsonb_populate_record(NULL::user_profile, data_column)).* 
            FROM raw_json_table;
  5. Handle Partial Data: If the JSONB object is missing a key that exists in the table, PostgreSQL will simply set that column to NULL for that record. If the JSONB object contains keys that do not exist in the table, those extra keys are ignored.

Common Mistakes

  • Using json_populate_record instead of jsonb_populate_record: While both exist, jsonb is significantly faster for processing and is the standard for modern PostgreSQL installations. Ensure you are using the b version for performance.
  • Mismatched Data Types: If the JSONB value cannot be cast to the target column type (e.g., trying to put a string "abc" into an INTEGER column), the query will fail with a data type mismatch error.
  • Forgetting the NULL::type cast: The function requires a record of the target type. If you don't provide NULL::your_table_name, PostgreSQL won't know which columns to map the JSON keys to.
  • Confusing it with jsonb_to_record: jsonb_to_record requires you to manually define the columns in the function call (e.g., jsonb_to_record(...) AS x(name text, age int)), whereas jsonb_populate_record uses an existing table or type definition.

Tips

  • Use for Data Migration: This function is ideal for "staging" data. You can import raw JSON into a temporary table and then use INSERT INTO target_table SELECT (jsonb_populate_record(NULL::target_table, json_col)).* FROM staging_table; to move data into a relational schema.
  • Combine with LATERAL: When dealing with arrays of JSON objects, use jsonb_array_elements combined with a CROSS JOIN LATERAL to populate multiple records from a single JSONB array.
  • Indexing: Remember that populating a record happens at runtime. If you find yourself calling this function frequently in WHERE clauses, consider creating a GIN index on the original JSONB column or creating a materialized view of the populated data.

Troubleshooting

If the function is not working as expected, try these steps:

  • Verify Column Names: Check that the keys in your JSONB object exactly match the column names of the target table (case-sensitivity matters). If your JSON keys are camelCase and your table columns are snake_case, the mapping will fail.
  • Check for Type Mismatches: If you get an "invalid input syntax" error, inspect the JSON value. Ensure that numbers are not wrapped in quotes if the target column is an integer.
  • Validate JSONB Format: Ensure the input is actually JSONB. If you are using a JSON type, explicitly cast it: json_column::jsonb.
  • Check Permissions: Ensure the user executing the query has SELECT permissions on the table used as the record template.

Frequently Asked Questions

What is the difference between jsonb_populate_record and jsonb_to_record?

jsonb_populate_record uses an existing table or composite type to define the output columns. jsonb_to_record requires you to explicitly define the columns and their types in the AS clause of the query.

Does this function modify the original table?

No. It is a SELECT function that returns a virtual record. It does not change the data in your database unless you use the result inside an INSERT or UPDATE statement.

Can I use this with a custom type instead of a table?

Yes. If you have created a composite type using CREATE TYPE my_type AS (...), you can use NULL::my_type as the first argument.

What happens if the JSON contains extra fields?

Any keys in the JSONB object that do not have a corresponding column name in the target record/table are simply ignored and discarded from the result.

Will this work with nested JSON objects?

It only populates the top level of the record. If a column in your target table is also a JSONB type, the nested JSON object will be placed into that column as a JSONB value, rather than being further flattened.