What is the best way to convert a boolean field from a JSONB object to a regular bool type in Postgres?
For example, I have a JSON object {"foo": true} that I can use in Postgresql. For example: select ('{"foo": true}'::jsonb); which gives me something like JSONB.
Now I want to extract the foo field as a boolean. If I do this:
select ('{"foo": true}'::jsonb)->'foo'; I am returning something like JSONB.
But I can not use JSONB for inference. If instead:
select ('{"foo": true}'::jsonb)->>'foo';
I will return to the type string. From this I can convert to logical. (For instance:)
select (('{"foo": true}'::jsonb)->>'foo')::bool;
But it seems a little icky going from the inner view to the line, and then back to another inner view.
Is it possible to go directly to bool?
My other current best work around:
select (('{"foo": true}'::jsonb)->'foo') = 'true'::jsonb;
but it also seems a little wrong.
source share