Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between jsonb type cast and to_jsonb in postgresql

Tags:

postgresql

Why do these two queries give different result in postgresql ?

select '{"items":["foo", "bar"]}'::jsonb->'items';

select to_jsonb('{"items":["foo", "bar"]}'::text)->'items';

the first one returns: ["foo", "bar"] and the second one returns [NULL]

like image 539
yucer Avatar asked Dec 30 '25 09:12

yucer


1 Answers

The documentation for to_jsonb() says this (emphasis mine):

Converts any SQL value to json or jsonb. Arrays and composites are converted recursively to arrays and objects (multidimensional arrays become arrays of arrays in JSON). Otherwise, if there is a cast from the SQL data type to json, the cast function will be used to perform the conversion; otherwise, a scalar JSON value is produced. For any scalar other than a number, a Boolean, or a null value, the text representation will be used, with escaping as necessary to make it a valid JSON string value.

In other words, it isn't parsing JSON from string, it's creating a JSON string from your text.

select 
    to_jsonb('{"items":["foo", "bar"]}'::text),
    to_jsonb('{"items":["foo", "bar"]}'::text)->'items';
to_jsonb ?column?
"{\"items\":[\"foo\", \"bar\"]}"
like image 141
Álvaro González Avatar answered Jan 01 '26 18:01

Álvaro González