在下面的查询中,$isComplete和$isValid作为字符串返回.但是,它们会另存为布尔值.如何获取这些字段的布尔表示形式以返回?

query =
    "SELECT
        data #>> '{id}' AS id,
        data #>> '{name}' AS name,
        data #>> '{curator}' AS curator,
        data #>  '{$isValid}' as \"$isValid\",
        data #>  '{customer}' as customer,
        data #>  '{$createdTS}' as \"$createdTS\",
        data #>  '{$updatedTS}' as \"$updatedTS\",
        data #>  '{$isComplete}' as \"$isComplete\",
        (count(keys))::numeric as \"numProducts\"
    FROM
      appointment_intakes,
      LATERAL jsonb_object_keys(data #> '{products}') keys
    GROUP BY id"

推荐答案

只需将文本转换为布尔值:

create table jsonb_test (id int, data jsonb);
insert into jsonb_test values
(1, '{"is_boolean" : true}'),
(2, '{"is_boolean" : false}');

select id, data, (data->>'is_boolean')::boolean as is_boolean
from jsonb_test
where (data->>'is_boolean')::boolean

 id |          data          | is_boolean 
----+------------------------+------------
  1 | {"is_boolean": true}   | t
(1 row)

请注意,您还可以将其他json文本值强制转换为布尔值,例如:

insert into jsonb_test values
(3, '{"is_boolean" : "true"}'),
(4, '{"is_boolean" : "false"}'),
(5, '{"is_boolean" : "t"}'),
(6, '{"is_boolean" : "f"}'),
(7, '{"is_boolean" : "on"}'),
(8, '{"is_boolean" : "off"}');

select id, data, (data->>'is_boolean')::boolean as is_boolean
from jsonb_test
where (data->>'is_boolean')::boolean

 id |          data          | is_boolean 
----+------------------------+------------
  1 | {"is_boolean": true}   | t
  3 | {"is_boolean": "true"} | t
  5 | {"is_boolean": "t"}    | t
  7 | {"is_boolean": "on"}   | t
(4 rows)

了解布尔类型in the documentation.的有效文本


使现代化

Postgres 11将JSONB标量的强制转换添加到数值和布尔数据类型.此查询仅适用于regular个布尔JSONB标量(即truefalse):

select id, data, (data->'is_boolean')::boolean as is_boolean
from jsonb_test
where (data->'is_boolean')::boolean

Postgresql相关问答推荐

端口5432失败:致命:数据库xxx&不存在.在PostgreSQL数据库中

使用doobie,如何将Scala case类映射到带有类型tstzmultirange的PostgreSQL列?

如何在 spring/JPA 中记录表和列名以防数据库错误

gorm 不生成字符串列

在 PostgreSQL 中返回插入的行

Rails 迁移:PostgreSQL 上的 Bigint 似乎失败了?

Postgres 删除表语法错误

H2 postgresql mode模式似乎不起作用

从 Select 中创建一个临时表,如果表已经存在则插入

在 postgreSQL 中更改序列名称

返回 array_agg() 中的第一个元素

如何使用 PostgreSQL 触发器来存储更改(SQL 语句和行更改)

PostgreSQL:从转储中恢复数据库 - 语法错误

使用 Spring、Hibernate 和 C3P0 管理多租户 Web 应用程序中的连接池

判断 PostgreSQL 中的角色是否设置了密码

用于将布尔列排序为 true、null、false 的 SQL

使用 cte (postgresql) 的结果更新

postgresql NOT ILIKE 子句不包含空字符串值

如何为 Postgresql 中的所有数据库创建具有只读权限的用户?

PostgreSQL 中 from dual 的等价性