Postgres json_populate_record() function
Casts a JSON object to a record
The json_populate_record
function is used to populate a record type with values from a JSON
object. It is useful for parsing JSON
data received from external sources, particularly when merging it into an existing record.
Function signature
This function takes two arguments: a base record of a row type (which can even be a NULL
record) and a JSON
object. It returns the record updated with the JSON
values.
Example usage
Consider a database table that tracks employee information. When you receive employee information as JSON
records, you can use json_populate_record
to ingest the data into the table.
Here we create the employees
table with some sample data.
To illustrate, we start with a NULL
record and cast the input JSON
payload to the employees
record type.
This query returns the following result:
Advanced examples
json_populate_record
Handling partial data with For data points where the JSON
objects have missing keys, json_populate_record
can still cast them into legible records.
Say we receive records for a bunch of employees who are known to be in Sales, but the department
field is missing from the JSON
payload. We can use json_populate_record
with the default value specified for a field while the other fields are populated from the JSON
payload, as in this example:
This query returns the following:
json_populate_record
Working with custom types in The base record doesn't need to have the type of a table row and can be a custom Postgres type too. For example, here we first define a custom type address
and use json_populate_record
to cast a JSON
object to it:
This query returns the following result:
Additional considerations
Alternative options
- json_to_record - It can be used similarly, with a couple differences.
json_populate_record
can be used with a base record of a pre-defined type, whereasjson_to_record
needs the record type defined inline in theAS
clause. Further,json_populate_record
can specify default values for missing fields through the base record, whereasjson_to_record
must assign them NULL values. json_populate_recordset
- It can be used similarly to parseJSON
, the difference being that it returns a set of records instead of a single record. For example, if you have an array ofJSON
objects, you can usejson_populate_recordset
to convert each object into a new row.- jsonb_populate_record - It has the same functionality to
json_populate_record
, but acceptsJSONB
input instead ofJSON
.
Resources
Last updated on