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

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;

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

你尝试过这个吗:(jsoncolumn -> 'exists')::boolean = true - user330315
@a_horse_with_no_name 是的,我试过了。它也没有起作用。 - BanzaiTokyo
2个回答

4
以下是验证JSON(b)布尔值的所有有效组合:
以下是验证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

0

将值作为文本获取,然后转换为布尔值:

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

有效的布尔字面量


我的问题是如何查询值是否为真,而不是检查它是否为布尔值。如果我的问题不够清晰,我很抱歉。 - BanzaiTokyo
那只是为了展示如何获取布尔值而不是JSON。 您可以按预期使用它。 - Clodoaldo Neto
这不起作用。你无法使用这种方法区分 {"exists": "true"}{"exists": true} 之间的区别。 - user9645

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接