2

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?

2
  • Did you try: (jsoncolumn -> 'exists')::boolean = true? Sep 14, 2016 at 14:37
  • @a_horse_with_no_name yes, I have. it didn't work either. Sep 14, 2016 at 14:51

2 Answers 2

3

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
0

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

3
  • my question is how to query if the value is true rather than check if it is a boolean. sorry if it was unclear from my question. Sep 14, 2016 at 16:05
  • That was to show how to get a boolean and not a json. You can just use it as intended. Sep 14, 2016 at 16:32
  • This doesn't work. You can't tell the difference between {"exists": "true"} and {"exists": true} using this method.
    – user9645
    Oct 1, 2018 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.