比较PostgreSQL 9.3 json对象中的布尔值

时间:2016-09-14 14:32:36

标签: json postgresql postgresql-9.3

有没有其他方法来匹配PostgreSQL(版本9.3 )json对象的布尔值而不将其转换为字符串?

我的意思是: 该表在其jsoncolumn列中包含以下对象:

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

以下查询获取记录(请注意,exists值将作为带->>的文本提取):

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

而且这个没有:

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

我想知道是否有更合适的方法来进行布尔比较?

2 个答案:

答案 0 :(得分:2)

这里'所有有效的组合来验证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

答案 1 :(得分:0)

获取文本的值,然后转换为boolean:

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

Valid boolean literals