我正在尝试将数据从Postgres DB提取到JSON文件。这里的问题是,我需要将多个层次结构中的数据加载到JSON文件中。
任何在 postgres SQL查询或python 中实现此目标的解决方案将不胜感激。
我尝试在一个级别上执行此操作,并成功通过了postgres上的json_agg()查询,但不确定如何在2个以上级别上执行此操作。
这是我的postgres代码:
select
json_build_object('column1',json_agg(
json_build_object('name',column1,'column2',column2)))
table1
from table;
which gives me :
[columns1:
{column2:value},
{column2:value2}
]
But what i need is:
eg: column1 column2 column3
4 1 4
4 4 5
4 1 9
2 3 7
3 1 8
1 1 1
3 1 6
output:
[
column1:4[{
column2:1[{
column3:4,
colun3:9}]
},
{ column2:4
[{
column3:5
}]
}]]
答案 0 :(得分:0)
这里有两种不同的变体,因为您的输出不是有效的JSON,因此很难猜测您想要哪种格式:
下面的两个变体都具有相同的查询结构,只是它们创建JSON对象的方式不同。
要获得更高级别的层次结构,您将需要更多类似agg_c3
的CTE,或者如果愿意,可以重写查询以使用嵌套的子选择(但比CTE难读)。
包装的键值
WITH
my_table (col1, col2, col3) AS (
VALUES (4,1,4), (4,4,5), (4,1,9), (2,3,7), (3,1,8), (1,1,1), (3,1,6)
),
agg_c3 AS (
SELECT col1, col2, jsonb_build_object('column3', jsonb_agg(jsonb_build_object('value', col3))) AS col3
FROM my_table
GROUP BY 1, 2
),
agg_c2 AS (
SELECT col1, jsonb_build_object('column2', jsonb_agg(jsonb_build_object('value', col2) || col3)) AS col2
FROM agg_c3
GROUP BY 1
)
SELECT jsonb_build_object('column1', jsonb_agg(jsonb_build_object('value', col1) || col2)) AS json_object
FROM agg_c2
;
...返回:
{
"column1": [
{
"value": 1,
"column2": [
{
"value": 1,
"column3": [
{
"value": 1
}
]
}
]
},
{
"value": 3,
"column2": [
{
"value": 1,
"column3": [
{
"value": 8
},
{
"value": 6
}
]
}
]
},
{
"value": 2,
"column2": [
{
"value": 3,
"column3": [
{
"value": 7
}
]
}
]
},
{
"value": 4,
"column2": [
{
"value": 1,
"column3": [
{
"value": 4
},
{
"value": 9
}
]
},
{
"value": 4,
"column3": [
{
"value": 5
}
]
}
]
}
]
}
仅值
WITH
my_table (col1, col2, col3) AS (
VALUES (4,1,4), (4,4,5), (4,1,9), (2,3,7), (3,1,8), (1,1,1), (3,1,6)
),
agg_c3 AS (
SELECT col1, col2, jsonb_agg(col3) AS col3
FROM my_table
GROUP BY 1, 2
),
agg_c2 AS (
SELECT col1, jsonb_agg(jsonb_build_object(col2::text, col3)) AS col2
FROM agg_c3
GROUP BY 1
)
SELECT jsonb_agg(jsonb_build_object(col1::text, col2)) AS json_object
FROM agg_c2
;
...返回:
[
{
"1": [
{
"1": [
1
]
}
]
},
{
"3": [
{
"1": [
8,
6
]
}
]
},
{
"2": [
{
"3": [
7
]
}
]
},
{
"4": [
{
"1": [
4,
9
]
},
{
"4": [
5
]
}
]
}
]