【问题标题】:Compare boolean values in PostgreSQL 9.3 json objects比较 PostgreSQL 9.3 json 对象中的布尔值
【发布时间】:2016-09-15 00:08:00
【问题描述】:

有没有其他方法可以匹配来自 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
  • @a_horse_with_no_name 是的,我有。它也没有工作。

标签: json postgresql postgresql-9.3


【解决方案1】:

以下是验证 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

【讨论】:

    【解决方案2】:

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

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

    Valid boolean literals

    【讨论】:

    • 我的问题是如何查询该值是否为真,而不是检查它是否为布尔值。抱歉,如果我的问题不清楚。
    • 那是为了展示如何获取布尔值而不是 json。您可以按预期使用它。
    • 这不起作用。使用这种方法你无法区分{"exists": "true"}{"exists": true}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    相关资源
    最近更新 更多