Sub topic 13
Moving values between SQL types and JSONB
This chapter assumes you know the -> and ->> operators, the difference between json and jsonb, and the cast syntaxes from earlier chapters. It covers how SQL values become JSONB, how JSONB values come back out, and where the conversions fail.
JSONB has its own small type system
A jsonb value is always one of six kinds: object, array, string, number, boolean or null. Every conversion between SQL and JSONB is a mapping between these kinds and PostgreSQL types. Use jsonb_typeof to see which kind a value is.
SELECT jsonb_typeof('{"a": 1}') AS obj,
jsonb_typeof('[1, 2]') AS arr,
jsonb_typeof('"hi"') AS str,
jsonb_typeof('12.5') AS num,
jsonb_typeof('true') AS bool,
jsonb_typeof('null') AS nul;The result is object, array, string, number, boolean and null.
The two extraction operators return different SQL types:
| Operator | Returns | JSON `null` becomes |
|---|---|---|
| `->` | `jsonb` | the JSON value `null` (still a `jsonb` value) |
| `->>` | `text` | SQL `NULL` |
That difference decides which conversion path you use.
Text to JSONB: parsing, not wrapping
Casting text to jsonb parses the string as JSON. It does not wrap the string as a JSON string. The same text can produce two different results depending on the path you take.
SELECT '42'::jsonb AS parsed,
to_jsonb('42'::text) AS wrapped,
jsonb_typeof('42'::jsonb) AS parsed_type,
jsonb_typeof(to_jsonb('42'::text)) AS wrapped_type;parsed is the number 42. wrapped is the string "42". Use the cast when you hold JSON text, and to_jsonb when you hold a SQL value.
Invalid JSON text raises invalid input syntax for type json. On PostgreSQL 16 and later you can test first:
SELECT pg_input_is_valid('{"a": 1}', 'jsonb') AS good,
pg_input_is_valid('{a: 1}', 'jsonb') AS bad;SQL values to JSONB with to_jsonb
to_jsonb(anyelement) picks the JSON kind from the SQL type.
| SQL type | JSONB kind |
|---|---|
| `integer`, `numeric`, `float8` | number |
| `boolean` | boolean |
| `text`, `varchar`, `char` | string |
| `date`, `timestamp`, `timestamptz` | string in ISO 8601 form |
| arrays | array |
| composite (row) types | object |
| anything else | string, using the type's text output |
SELECT to_jsonb(ROW(1, 'x'::text, true)) AS anon_row,
to_jsonb(ARRAY[1, 2, 3]) AS arr,
to_jsonb(DATE '2026-11-27') AS d,
to_jsonb(TIMESTAMPTZ '2026-11-27 10:00:00+00') AS ts;Dates and timestamps become strings. JSON has no date type, so nothing stops a reader from interpreting them differently. A timestamptz is rendered using the session TimeZone setting. Set it explicitly (for example SET TIME ZONE 'UTC') before you serialize timestamps that other systems will read.
JSONB to SQL values: two routes
Suppose a table stores documents whose fields are not always typed consistently.
CREATE TABLE orders (
id serial PRIMARY KEY,
doc jsonb NOT NULL
);
INSERT INTO orders (doc) VALUES
('{"qty": 5, "price": 9.5, "paid": true}'),
('{"qty": "7", "price": "3", "paid": "false"}'),
('{"qty": null, "price": 1.25}');Route 1: cast the jsonb value directly
Since PostgreSQL 11 you can cast a jsonb scalar straight to integer, bigint, numeric, float4, float8 or boolean. The cast succeeds only when the JSON kind matches the target.
SELECT (doc -> 'qty')::int AS qty,
(doc -> 'price')::numeric AS price,
(doc -> 'paid')::boolean AS paid
FROM orders
WHERE id = 1;Run the same query for id = 2 and it fails with cannot cast jsonb string to type integer. The value "7" is a JSON string, even though it looks like a number. For id = 3 the error is cannot cast jsonb null to type integer. Objects and arrays fail the same way.
A number that does not fit the target is converted as numeric would be. '12.5'::jsonb::int rounds to 13, and a value that is too large raises integer out of range.
Route 2: extract as text, then cast
->> returns text, so the ordinary text conversion rules apply. JSON strings and numbers both work, and JSON null becomes SQL NULL.
SELECT id,
(doc ->> 'qty')::int AS qty,
(doc ->> 'price')::numeric AS price,
(doc ->> 'paid')::boolean AS paid
FROM orders
ORDER BY id;This runs for all three rows. Row 2 gives 7, 3 and false. Row 3 gives NULL for qty, and NULL for paid because the key is missing.
Route 2 has its own limit. Text goes through the target type's input function, so '12.5' cast to int fails with invalid input syntax for type integer, just as it does for any text. A JSON number like 12.5 therefore behaves differently on the two routes: the direct cast rounds it, and the text cast rejects it.
Guarding against mixed types
When a key holds different kinds across rows, test the kind before you cast.
SELECT id,
CASE jsonb_typeof(doc -> 'qty')
WHEN 'number' THEN (doc -> 'qty')::int
WHEN 'string' THEN (doc ->> 'qty')::int
END AS qty
FROM orders
ORDER BY id;Rows with JSON null or a missing key fall through to NULL. This is safe because CASE evaluates only the branch that matches. Avoid moving the same cast into a WHERE clause or a subquery that the planner may flatten, since the planner may evaluate it before your guard.
On PostgreSQL 16 and later you can also validate text before casting:
SELECT pg_input_is_valid(doc ->> 'qty', 'integer') AS qty_ok
FROM orders
ORDER BY id;Row 3 returns NULL rather than false, because pg_input_is_valid returns NULL for a NULL input.
Converting a whole object to columns
When you want many fields at once, let PostgreSQL do the conversion per column. jsonb_to_record takes a column definition list and converts each field with the target type's input function.
SELECT t.*
FROM orders o,
jsonb_to_record(o.doc) AS t(qty int, price numeric, paid boolean)
ORDER BY o.id;This accepts the string "7" for qty and the string "false" for paid, so it follows the same rules as Route 2. Keys that are absent give NULL. A value that cannot be converted still raises an error for the whole statement. jsonb_to_recordset does the same for a JSON array of objects, and jsonb_populate_record fills an existing row type.
Casts and indexes on JSONB expressions
A cast on a JSONB expression is an expression, so a plain index on doc will not help. Index the exact expression instead:
CREATE INDEX orders_qty_idx ON orders (((doc ->> 'qty')::int));
SELECT id FROM orders WHERE (doc ->> 'qty')::int = 5;The query must repeat the expression exactly. Writing doc ->> 'qty' = '5' compares text and does not match this index. A single malformed value makes the index build fail, so clean the data or add a guarded expression first.
Summary of rules
->returnsjsonb;->>returnstext, and JSONnullbecomes SQLNULL.- A direct
jsonbcast works only when the JSON kind matches the target type. - A text cast follows normal text input rules, so
12.5cannot becomeinteger. '42'::jsonbparses;to_jsonb('42'::text)wraps a string.- Dates and timestamps become ISO strings, and you convert them back through text.
- Index the exact cast expression that your queries use.
Exercise
A column doc jsonb holds {"age": "31"} in some rows and {"age": 31} in others. Write an expression that returns the age as an integer for both shapes, and explain why (doc -> 'age')::int is not enough.
Show answer
Use (doc ->> 'age')::int. The ->> operator returns text for both the JSON string "31" and the JSON number 31, and the text cast then succeeds. The expression (doc -> 'age')::int casts the jsonb value directly, which works for the number row but raises cannot cast jsonb string to type integer for the string row.
Exercise
What do '7'::jsonb and to_jsonb('7'::text) return, and what does jsonb_typeof report for each?
Show answer
'7'::jsonb parses the text as JSON and returns the number 7, so jsonb_typeof reports number. to_jsonb('7'::text) wraps a SQL text value and returns the JSON string "7", so jsonb_typeof reports string.