jsonb_build_object(...) — Build a JSON object by hand
Last updated: 2026-11-04
jsonb_build_object(...) — Build a JSON object by hand
jsonb_build_object() constructs a JSONB object from alternating key and value arguments, where each value can be any SQL type and is converted automatically. Where to_jsonb() converts a whole row, this lets you decide exactly which fields appear and under which names — handy when assembling an API response payload.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
jsonb_build_object(key text, value any [, ...]) → jsonb
⚙️ Parameters
| key text | The key name in the JSON object, supplied in alternating order. Type text. |
|---|---|
| value any | The value paired with the preceding key; any SQL type is converted. |
Returns:jsonb — the constructed object. If a key is repeated, the later value wins.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
id | order_json
----+----------------------------------------------
1 | {"qty": 2, "sku": "HUB-001", "total": 90.00}
2 | {"qty": 5, "sku": "CBL-002", "total": 62.50}
(2 rows)
📌 Key Points
- Keys and values must come in pairs; a mismatch raises an error immediately.
- JSONB reorders the keys, so the order you see in the output is not the order you passed them in.
- For a nested object, pass the result of another jsonb_build_object() as a value.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QShould I use jsonb_build_object() or json_build_object()?
APrefer jsonb_build_object(): it returns binary JSONB, which is smaller, compares faster and supports indexing and the -> operators. Use json_build_object() only when you need to preserve the original text layout.