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.

Kindfunction
Example LanguageSQL

📝 Syntax

jsonb_build_object(key text, value any [, ...]) → jsonb

⚙️ Parameters

key textThe key name in the JSON object, supplied in alternating order. Type text.
value anyThe 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏