PostgreSQL 18 reference · JSON Functions
PostgreSQL TO_JSONB() Function
Convert any SQL value, including a whole row, to jsonb. Rows become objects with column names as keys.
PostgreSQL 18 Since 9.5
Syntax
to_jsonb(anyelement)
Parameters
| Parameter | Description |
|---|---|
anyelement |
Any value, row or array. |
Return value
jsonb.
Examples
SELECT to_jsonb(c) AS row_as_json
FROM categories AS c
WHERE category_id = 1;
Output
row_as_json
-------------------------------------
{"name": "Books", "category_id": 1}
(1 row)Run this on your computer — see “Get Started” for setup.
SELECT to_jsonb(ARRAY[1, 2]) AS arr, to_jsonb('he said "hi"'::text) AS str;
Output
arr | str --------+------------------ [1, 2] | "he said \"hi\"" (1 row)
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| PostgreSQL 9.5 | Added |
Related
JSONB_BUILD_OBJECT()· Build a JSON object from alternating keys and values. json_build_object() returns json instead of jsonb.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