【问题标题】:In postgresql, how can I return a boolean value instead of string on a jsonb key?在 postgresql 中,如何在 jsonb 键上返回布尔值而不是字符串?
【发布时间】:2016-01-07 14:24:15
【问题描述】:

在下面的查询中,$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"

【问题讨论】:

    标签: json postgresql jsonb


    【解决方案1】:

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

    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 标量的转换添加到数字和布尔数据类型。此查询仅适用于 常规 布尔 JSONB 标量(即 truefalse):

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

    【讨论】:

      猜你喜欢
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 2021-12-11
      • 2013-08-17
      • 2015-03-26
      • 1970-01-01
      相关资源
      最近更新 更多