PostgreSQL – JSON_OBJECT Function
The json_object
in PostgreSQL function is used to create a JSON object from a set of key-value pairs. This function was introduced in PostgreSQL 12 and provides a convenient way to create JSON objects directly within SQL queries.
The basic syntax of the json_object
function is as follows:
json_object(key1 value1, key2 value2, ..., keyN valueN)
Here’s a simple example of how you can use the json_object
function:
SELECT json_object('name' 'John', 'age' 30, 'city' 'New York');
This would produce a JSON object like this:
{"name": "John", "age": 30, "city": "New York"}
You can also use expressions as values in the json_object
function:
SELECT json_object('name' 'John', 'age' (EXTRACT(YEAR FROM current_date) - 1990));
In this example, the value for the ‘age’ key is calculated using the current year and subtracting 1990.