PostgreSQL 18 reference · JSON Functions
PostgreSQL JSONB_BUILD_OBJECT() Function
Build a JSON object from alternating keys and values. json_build_object() returns json instead of jsonb.
PostgreSQL 18 Since 9.5
Syntax
jsonb_build_object(key1, value1, ...)
Parameters
| Parameter | Description |
|---|---|
key, value |
Pairs; SQL NULL becomes JSON null. |
Return value
jsonb.
Examples
SELECT jsonb_build_object('id', customer_id, 'name', name, 'email', email) AS customer
FROM customers
WHERE customer_id IN (4, 5);
Output
customer
-------------------------------------------------------------------
{"id": 4, "name": "Linus Torvalds", "email": "[email protected]"}
{"id": 5, "name": "Margaret Hamilton", "email": null}
(2 rows)Run this on your computer — see “Get Started” for setup.
SELECT jsonb_build_object('tags', jsonb_build_array('a', 'b'), 'count', 2) AS nested;
Output
nested
----------------------------------
{"tags": ["a", "b"], "count": 2}
(1 row)Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| PostgreSQL 9.5 | Added |
In other languages
JSON_OBJECT()· SQLite
Related
JSONB_BUILD_ARRAY()· Build a JSON array from the arguments, which may be of different types.TO_JSONB()· Convert any SQL value, including a whole row, to jsonb. Rows become objects with column names as keys.JSONB_AGG()· Aggregate a group's values or rows into a JSON array. json_agg() does the same but returns json.- SQL String Functions · tutorial