2016-09-14 61 views
2

是否有任何其他方式來匹配PostgreSQL的布爾值(版本9.3)json對象而不將其轉換爲字符串?比較PostgreSQL中的布爾值9.3 json對象

我的意思是: 表包含在其jsoncolumn列下列對象:

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

以下查詢獲取記錄(注意:exists值取爲與->>文本):

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

,這一次沒有:

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

我想知道是否有更合適的方法來進行布爾比較?

+0

你有沒有嘗試:'(jsoncolumn - >'exists'):: boolean = true'? –

+0

@a_horse_with_no_name是的,我有。它也沒有工作。 – BanzaiTokyo

回答

0

獲取的值作爲文本,然後轉換爲布爾:

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

Valid boolean literals

+0

我的問題是如何查詢值是否爲真,而不是檢查它是否是布爾值。對不起,如果我的問題不清楚。 – BanzaiTokyo

+0

這是爲了展示如何獲得布爾值而不是json。你可以按照預期使用它。 –

2

我這裏還有所有的有效組合,以驗證JSON(B)布爾:

-- 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