JSONPostgreSQL only

TO_JSONB

Converts a value — a number, text, an array or a whole table row — to JSON.

Syntax

TO_JSONB(<value>)

A number becomes a JSON number, text a JSON string, an array a JSON array. If you pass the table row itself (its alias in the query), you get an object with all the columns — handy for sending a record to the application in one field or saving it to a change log.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

A number, text and an array
SELECT TO_JSONB(42) AS number,
TO_JSONB('Emma'::text) AS text_value,
TO_JSONB(ARRAY['sql', 'postgres']) AS array_value;
numbertext_valuearray_value
42Emma["sql","postgres"]

The result table shows the JSON string without quotes; in psql it would be "Emma".

A whole row as one object
SELECT TO_JSONB(e) AS employee
FROM employees e;
employee
{"name":"Emma","bonus":300,"phone":"+44 7700 900123","salary":1200,"department":"backend"}
{"name":"Liam","bonus":null,"phone":null,"salary":1000,"department":"backend"}
{"name":"Olivia","bonus":150,"phone":"+44 7700 900456","salary":1350,"department":"frontend"}
{"name":"Noah","bonus":null,"phone":"+44 7700 900789","salary":950,"department":"frontend"}
{"name":"Sophia","bonus":200,"phone":null,"salary":1200,"department":"design"}

Here e isn't a column but the whole row of the employees table.

A column value into JSONB_SETAdvanced
SELECT name,
JSONB_SET('{"name": null}', '{name}', TO_JSONB(name)) AS doc
FROM employees;
namedoc
Emma{"name":"Emma"}
Liam{"name":"Liam"}
Olivia{"name":"Olivia"}
Noah{"name":"Noah"}
Sophia{"name":"Sophia"}

JSONB_SET expects JSON, so we first convert the name from the column with TO_JSONB.

Watch out

A text literal without a type won't work: TO_JSONB('Emma') throws could not determine polymorphic type because input has type unknown. Give it a type: TO_JSONB('Emma'::text).

TO_JSONB(NULL) is an SQL NULL, not a JSON null. If you need null itself, write 'null'::jsonb.

Dates become strings in ISO format: TO_JSONB(DATE '2026-09-13') gives "2026-09-13", and a timestamp gets a T in the middle: "2026-09-13T15:47:00".