如何将hstore []列转换为jsonb?

时间:2016-01-04 22:41:35

标签: postgresql hstore jsonb

我想要将hstore[]列转换为jsonb,但似乎我无法在这两种类型之间进行转换。 (我可以从普通hstore投射而没有问题)。

例如,如果我在单元格中有'{foo=>bar,baz=>quux}'::hstore[],我希望将其转换为'[{"foo":"bar","baz":"quux"}]'::jsonb

如何在postgresql中完成?

1 个答案:

答案 0 :(得分:0)

通常,您可以使用ALTER TABLE ... ALTER COLUMN ... TYPEUSING子句进行具有额外逻辑的转换(或转换,其类型之间没有明确的转换)。

SELECT变换值的表达式为:

select (select json_agg(hstore_to_json(h)) from unnest(hstore_array) h)::jsonb
from   table_name

(或者,您可以使用hstore_to_json_loose(h)获取数字和布尔值,而不是始终获取字符串。)

不幸的是,你不能在这个USING子句中使用子选择,所以你可以这样做:

  1. 创建临时功能&在USING

    中使用它
    create function temp_hstore_array_to_jsonb(hstore[])
      returns jsonb
      language sql
      immutable
    as $func$
      select json_agg(hstore_to_json(h))::jsonb
      from   unnest($1) h
    $func$;
    
    alter table table_name
      alter column hstore_array
      type jsonb
      using temp_hstore_array_to_jsonb(hstore_array);
    
    drop function temp_hstore_array_to_jsonb(hstore[]);
    
    -- optionally rename column
    
  2. 创建另一列,复制转换后的数据&删除原始列

    alter table table_name
      add column jsonb_copy jsonb;
    
    update table_name
    set    jsonb_copy = (select json_agg(hstore_to_json(h))
                         from   unnest(hstore_array) h)::jsonb;
    
    alter table table_name drop column hstore_array;
    
    -- optionally rename column back like the dropped one
    

    但是后面这个有一个弱点:旧列(要删除)可能有依赖对象,这可能使实际丢弃更加困难(CASCADE也会丢弃它们,但这可能不是你的意思要)。

相关问题