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]
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\"]}" |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With