Skip to content
the poor coder

json_populate_recordset

Poor Man
Published
Reading time
2 min read
On this page

hljs.initHighlightingOnLoad();

What is JSON_POPULATE_RECORDSET?#

JSON_POPULATE_RECORDSET is a PostgreSQL function that allows you to convert a JSON array to a set of rows with defined columns. This can be useful when you want to insert JSON data into a table or manipulate it in some other way.

How to use JSON_POPULATE_RECORDSET?#

Here is the basic syntax:

Text

JSON_POPULATE_RECORDSET(base anyelement, from_json text) 
RETURNS SETOF anyelement

The first argument is the base type of the resulting rows. The second argument is the JSON array text. You can also use the optional third argument to specify the columns:

Text

JSON_POPULATE_RECORDSET(base anyelement, from_json text, columns text[]) 
RETURNS SETOF anyelement

The columns argument should be an array of column names in the order they appear in the JSON array.

Example:#

Let's say we have a JSON array of people:

Text

[
  {"name": "John", "age": 25},
  {"name": "Jane", "age": 30},
  {"name": "Bob", "age": 40}
]

We can use JSON_POPULATE_RECORDSET to insert this data into a table:

Text

CREATE TABLE people (name varchar(50), age int);
INSERT INTO people SELECT * FROM JSON_POPULATE_RECORDSET(null::people, '[{"name": "John", "age": 25}, {"name": "Jane", "age": 30}, {"name": "Bob", "age": 40}]');

This will create a table called "people" with two columns: "name" and "age". It will then insert the data from the JSON array into the table.

Alternative:#

Another way to achieve the same thing is by using the json_array_elements function:

Text

CREATE TABLE people (name varchar(50), age int);
INSERT INTO people
SELECT (elem->>'name')::varchar(50), (elem->>'age')::int FROM json_array_elements('[{"name": "John", "age": 25}, {"name": "Jane", "age": 30}, {"name": "Bob", "age": 40}]') AS elem;

This will also create a table called "people" with two columns: "name" and "age". It will then insert the data from the JSON array into the table. However, this method requires you to manually extract each column from the JSON object.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC