2016-09-14 62 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