to_jsonb(anyelement) — Convert a value into JSONB
Last updated: 2026-11-04
to_jsonb(anyelement) — Convert a value into JSONB
to_jsonb() converts any SQL value into JSONB, and a whole row can be converted directly to get a JSON object holding every column. It is the usual way to export relational data as JSON for an API response, or to gather several rows into a single JSON array.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
to_jsonb(value anyelement) → jsonb
row_to_json(record [, pretty_bool]) → json
⚙️ Parameters
| value anyelement | The SQL value to convert; pass a table alias to convert an entire row at once. |
|---|
Returns:jsonb — the converted value. Numbers, booleans, text, arrays and nested objects all map correctly.
▶ 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 | product_json
----+--------------------------------------------------------------------
1 | {"id": 1, "name": "USB-C Hub", "price": 45.00, "in_stock": true}
2 | {"id": 2, "name": "HDMI Cable", "price": 12.50, "in_stock": false}
(2 rows)
📌 Key Points
- JSONB drops duplicate keys in an object and reorders the keys by length and then bytewise, so the output order is not the insertion order.
- A numeric becomes a JSON number with its scale preserved, and a timestamp becomes an ISO 8601 string.
- To gather several rows into an array use jsonb_agg(), for example jsonb_agg(to_jsonb(t)).
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QHow does to_jsonb() differ from to_json()?
Ato_json() returns json text preserving the original whitespace and key order, while to_jsonb() returns parsed binary JSONB — smaller, indexable and usable with the -> operators.