4

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? Commented Sep 14, 2016 at 14:37
  • @a_horse_with_no_name yes, I have. it didn't work either. Commented Sep 14, 2016 at 14:51

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

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 Comments

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.
That was to show how to get a boolean and not a json. You can just use it as intended.
This doesn't work. You can't tell the difference between {"exists": "true"} and {"exists": true} using this method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.