Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 552
BanzaiTokyo Avatar asked Oct 15 '25 15:10

BanzaiTokyo


1 Answers

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
like image 61
Kristo Mägi Avatar answered Oct 18 '25 07:10

Kristo Mägi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!