Postgre转换列jsonb在另一个表中,其中列是键

时间:2017-09-05 22:40:55

标签: python json postgresql jsonb

我需要在这种情况下使用python创建一个脚本,以获取一个表的列jsonb,创建另一个表,其中列是此json的所有可能键。

例如:

来自

id  | optional

1   | {"a":"4", "b":"5"}
2   | {}
3   | {"a":"8", "c":"9", "d":"9"}

id  |  a   |   b   |  c  |  d

1   |  4   |   5   |     |  
3   |  8   |       |  9  |  9

我使用此查询获得了密钥:

select jsonb_object_keys(optional) as key from table group by key

我在python中使用以下代码创建一个表,其中键为列

    connection = psycopg2.connect( host=host, database=database, user=user, password=password)
    try:      
        columns = "("
        for column in keys:
            columns+=column+" TEXT "+','
        columns = columns[0:len(columns)-1]
        columns += ");"
        query = "CREATE TABLE " + table +" "
        query +=  columns
        print query
        cur = connection.cursor()
        cur.execute(query)
        connection.commit()
        cur.close()

我使用此查询得到了我需要放在另一个表中的数据:

select id, optional->'a',...  from table where optional<>'{}'

在我的情况下,我有大约31个键,所以上面的查询很大,另一方面,如果我想将这个脚本重用于另一个案例,我可能需要更改此查询。

所以我想知道是否还有另一种方式更优雅,更通用。即使没有必要使用python,如果只有postgres它也对我有好处

有什么想法吗?

提前致谢

1 个答案:

答案 0 :(得分:2)

您可能对描述in this answer (see Generalized solution).

的Postgres解决方案感兴趣

示例源表:

drop table if exists my_table;
create table my_table(id int primary key, data jsonb);
insert into my_table values
(1, '{"a":"4", "b":"5"}'),
(2, '{}'),
(3, '{"a":"8", "c":"9", "d":"9"}');

使用该功能:

select create_jsonb_flat_view('my_table', 'id', 'data');

select * from my_table_view;

 id | a | b | c | d 
----+---+---+---+---
  1 | 4 | 5 |   | 
  2 |   |   |   | 
  3 | 8 |   | 9 | 9
(3 rows)

您可以根据平面视图创建新表:

create table my_new_table as
select *
from my_table_view
order by id;