我正在使用JSON中的API提取数据,格式类似于下面的示例数据。基本上每个“行”都是一个值数组。 API文档提前定义列及其类型。所以我知道col1是一个varchar,而col2是一个int。
CREATE TEMP TABLE dat (data json);
INSERT INTO dat
VALUES ('{"COLUMNS":["col1","col2"],"DATA":[["a","1"],["b","2"]]}');
我想在PostgreSQL 9.3中对此进行转换,以便最终得到:
col1 | col2
------------
a | 1
b | 2
使用json_array_elements
我可以:
SELECT json_array_elements(data->'DATA')
FROM dat
json_array_elements
json
---------
["a","1"]
["b","2"]
然后我无法弄清楚如何将JSON数组转换为PostgreSQL数组,这样我就可以执行unnest(ARRAY['a','1'])
答案 0 :(得分:8)
获得类似
的结果col1 | col2
------------
a | 1
b | 2
将需要一堆动态SQL,因为您事先不知道列的类型,也不知道列名。
您可以使用以下内容解压缩json:
SELECT
json_array_element_text(colnames, colno) AS colname,
json_array_element_text(colvalues, colno) AS colvalue,
rn,
idx,
colno
FROM (
SELECT
data -> 'COLUMNS' AS colnames,
d AS colvalues,
rn,
row_number() OVER () AS idx
FROM (
SELECT data, row_number() OVER () AS rn FROM dat
) numbered
cross join json_array_elements(numbered.data -> 'DATA') d
) elements
cross join generate_series(0, json_array_length(colnames) - 1) colno;
生成如下结果集:
colname | colvalue | rn | idx | colno
---------+----------+----+-----+-------
col1 | a | 1 | 1 | 0
col2 | 1 | 1 | 1 | 1
col1 | b | 1 | 2 | 0
col2 | 2 | 1 | 2 | 1
(4 rows)
然后,您可以使用此作为tablefunc模块中交叉表函数的输入,如下所示:
SELECT * FROM crosstab('
SELECT
to_char(rn,''00000000'')||''_''||to_char(idx,''00000000'') AS rowid,
json_array_element_text(colnames, colno) AS colname,
json_array_element_text(colvalues, colno) AS colvalue
FROM (
SELECT
data -> ''COLUMNS'' AS colnames,
d AS colvalues,
rn,
row_number() OVER () AS idx
FROM (
SELECT data, row_number() OVER () AS rn FROM dat
) numbered
cross join json_array_elements(numbered.data -> ''DATA'') d
) elements
cross join generate_series(0, json_array_length(colnames) - 1) colno;
') results(rowid text, col1 text, col2 text);
制造
rowid | col1 | col2
---------------------+------+------
00000001_ 00000001 | a | 1
00000001_ 00000002 | b | 2
(2 rows)
此处不保留列名称。
如果您使用的是9.4,则可以避免row_number()
来电并使用WITH ORDINALITY
,从而使其更加清晰。
由于您显然事先知道了列数及其类型,因此可以大大简化查询。
SELECT
col1, col2
FROM (
SELECT
rn,
row_number() OVER () AS idx,
elem ->> 0 AS col1,
elem ->> 1 :: integer AS col2
FROM (
SELECT data, row_number() OVER () AS rn FROM dat
) numbered
cross join json_array_elements(numbered.data -> 'DATA') elem
ORDER BY 1, 2
) x;
结果:
col1 | col2
------+------
a | 1
b | 2
(2 rows)
WITH ORDINALITY
如果您使用的是9.4,则可以使用WITH ORDINALITY
保持清洁:
SELECT
col1, col2
FROM (
SELECT
elem ->> 0 AS col1,
elem ->> 1 :: integer AS col2
FROM
dat
CROSS JOIN
json_array_elements(dat.data -> 'DATA') WITH ORDINALITY AS elements(elem, idx)
ORDER BY idx
) x;
答案 1 :(得分:0)
这段代码对我来说很好,也许对某人有用。
select to_json(array_agg(t))
from (
select text, pronunciation,
(
select array_to_json(array_agg(row_to_json(d)))
from (
select part_of_speech, body
from definitions
where word_id=words.id
order by position asc
) d
) as definitions
from words
where text = 'autumn'
) t
现金: https://hashrocket.com/blog/posts/faster-json-generation-with-postgresql