Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a JSONB value to boolean in Postgresql?

What is the best way to convert a boolean field from a JSONB object into a normal bool type in Postgres?

For example I have a JSON object {"foo": true}, which I can use in Postgresql. E.g.: select ('{"foo": true}'::jsonb); which gives me something of type JSONB.

Now I want to extract the foo field as a boolean. If I do:

select ('{"foo": true}'::jsonb)->'foo';

I get back something of type JSONB.

But, I can't cast JSONB to boolean. If instead of I do:

select ('{"foo": true}'::jsonb)->>'foo';

I will get back something of type string. From that I can convert to a boolean. (E.g:)

select (('{"foo": true}'::jsonb)->>'foo')::bool;

But that seems a bit icky going from internal representation to string, and then back to another internal representation.

Is there any to go directly to a bool?

My other current best work around seems to be:

select (('{"foo": true}'::jsonb)->'foo') = 'true'::jsonb;

but that also seems a bit wrong.

like image 524
benno Avatar asked Jan 28 '15 05:01

benno


People also ask

Can you index Jsonb Postgres?

JSONB and IndexesPostgreSQL can use indexes for the text results as compare operands. GIN index can be used by the GIN JSONB operator class.

What is Jsonb data type in PostgreSQL?

The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed.


1 Answers

You can use json_to_record:

select foo
from json_to_record('{"foo": true}') as x(foo bool);

I am not sure if that really saves you any internal casts, but it's the closest thing I know of in 9.4

like image 162
Sean Vieira Avatar answered Oct 21 '22 06:10

Sean Vieira