PostgreSQL jsonb_populate_record() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_populate_record()
function to populate the fields of a record type from a JSON object.
Introduction to the PostgreSQL jsonb_populate_record() function
The jsonb_populate_record()
function expands the top-level JSON object of type JSONB to a row of a specified composite type.
In other words, the jsonb_populate_record()
function converts a JSON object into a row of a specified composite type.
Here’s the basic syntax of the jsonb_populate_record()
function:
In this syntax:
target
is a composite type to which you want to expand the JSONB value.json_object
is a JSON object of the JSONB type that you want to expand.
The jsonb_populate_record()
function returns a record of the specified type with its fields populated using the key-value pairs from the JSON object.
PostgreSQL jsonb_populate_record() function examples
Let’s explore some examples of using the jsonb_populate_record()
function.
1) Basic jsonb_populate_record() function example
First, create a new type called person
:
Second, use the jsonb_populate_record()
function to expand the JSON object to a row of the person
type:
Output:
2) Using the jsonb_populate_record() function with table data
First, create a new table called employees
:
Second, insert some rows into the employees
table:
Third, use jsonb_populate_record()
to query the data from the employees
table in a structured format:
Output:
Summary
- Use the
jsonb_populate_record()
function to populate the fields of a record type or a custom composite type from a JSON object.