PostgreSQL – JSON_BUILD_OBJECT Function

The json_build_object function is used to create a JSON object from key-value pairs. It allows you to construct a JSON object by specifying keys and their corresponding values. Each key-value pair you provide becomes a property in the resulting JSON object.

Below is the basic syntax of using the json_build_object function:

json_build_object(key1, value1, key2, value2, ..., keyN, valueN)

Here’s an example of how you might use json_build_object:

SELECT json_build_object('name', 'John', 'age', 30, 'is_student', false);

This query would return a JSON object:

json_build_object 
----------------------------------------- 
{"name": "John", "age": 30, "is_student": false}

You can also use column values or expressions as values for the keys:

SELECT json_build_object('full_name', first_name || ' ' || last_name, 'email', email) FROM users;

This would create a JSON object for each row in the users table, containing the combined first_name and last_name as the value for the key 'full_name', and the email column as the value for the key 'email'.

Similar Posts