BanzaiTokyo
BanzaiTokyo

Reputation: 1404

Compare boolean values in PostgreSQL 9.3 json objects

Is there any other way to match a boolean value from a PostgreSQL (version 9.3) json object without converting it to string?

What I mean is: The table contains the following object in its jsoncolumn column:

'{"path":"mypath", "exists": true}'

the following query fetches the record (note that the exists value is fetched as text with ->>):

select * from thetable where jsoncolumn ->> 'exists' = 'true';

and this one doesn't:

select * from thetable where jsoncolumn -> 'exists' = true;

I wonder if there is a more appropriate way to do a boolean comparison?

Upvotes: 4

Views: 4026

Answers (2)

Kristo Mägi
Kristo Mägi

Reputation: 1684

Here're all the valid combinations to validate json(b) boolean:

-- This works only with jsonb, not with json because in Postgres json type is just a string.
SELECT $${ "exists": true }$$::jsonb -> 'exists' = 'true';
-[ RECORD 1 ]
?column? | t

-- All the following works with regular json as well with jsonb:
SELECT ( $${ "exists": true }$$::json ->> 'exists' )::boolean;
-[ RECORD 1 ]
bool | t

SELECT ( $${ "exists": true }$$::json ->> 'exists' )::boolean IS TRUE;
-[ RECORD 1 ]
?column? | t

SELECT ( $${ "exists": true }$$::json ->> 'exists' )::boolean = TRUE;
-[ RECORD 1 ]
?column? | t

Upvotes: 5

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125284

Get the value as text then cast to boolean:

select pg_typeof((j ->> 'exists')::boolean)
from (values ('{"path":"mypath", "exists": true}'::json)) v(j)
;
 pg_typeof 
-----------
 boolean

Valid boolean literals

Upvotes: 0

Related Questions