JSONPostgreSQL only

JSONB_BUILD_OBJECT

Builds a JSON object from key–value pairs.

Syntax

JSONB_BUILD_OBJECT(<key1>, <value1>, <key2>, <value2>, …)

The arguments come in pairs: a key, then its value. Numbers stay numbers, text becomes strings, NULL becomes null. Handy for sending data to the application in a single JSON field or gathering several columns into one object.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

An object from pairs
SELECT JSONB_BUILD_OBJECT('name', 'Emma', 'salary', 1200) AS employee;
employee
{"name":"Emma","salary":1200}
An object for each employee
SELECT JSONB_BUILD_OBJECT('name', name, 'department', department, 'phone', phone) AS employee
FROM employees;
employee
{"name":"Emma","phone":"+44 7700 900123","department":"backend"}
{"name":"Liam","phone":null,"department":"backend"}
{"name":"Olivia","phone":"+44 7700 900456","department":"frontend"}
{"name":"Noah","phone":"+44 7700 900789","department":"frontend"}
{"name":"Sophia","phone":null,"department":"design"}

Where there's no phone number, the JSON has null.

A value from the object — back out
SELECT JSONB_BUILD_OBJECT('name', 'Emma', 'salary', 1200) ->> 'name' AS name;
name
Emma

->> gets the value for a key as text.

Watch out

There must be an even number of arguments: JSONB_BUILD_OBJECT('name', 'Emma', 'salary') throws argument list must have even number of elements.

jsonb orders the keys itself and doesn't keep duplicates: JSONB_BUILD_OBJECT('b', 1, 'a', 2) shows {"a": 2, "b": 1}. The written order is kept by JSON_BUILD_OBJECT — without the B.

-> returns jsonb, and ->> returns text. To compare with a string or calculate, you need ->>, and for numbers a cast as well: (employee ->> 'salary')::int.