我在具有多行的表上使用OBJECT_CONSTRUCT
,如下所示:
COPY INTO @%mytable
FROM (
SELECT OBJECT_CONSTRUCT(
'id', id, 'first_name', first_name,
'last_name', last_name, 'city', city, 'state', state
) FROM mytable
)
FILE_FORMAT = (TYPE = JSON);
这会产生以下JSON输出:
{"city":"Salt Lake City","first_name":"Ryan","id":1,"last_name":"Dalton","state":"UT"}
{"city":"Birmingham","first_name":"Upton","id":2,"last_name":"Conway","state":"AL"}
{"city":"Columbus","first_name":"Kibo","id":3,"last_name":"Horton","state":"GA"}
但是,我想将产生的对象嵌套到JSON数组中,如下所示:
[
{"city":"Salt Lake City","first_name":"Ryan","id":1,"last_name":"Dalton","state":"UT"},
{"city":"Birmingham","first_name":"Upton","id":2,"last_name":"Conway","state":"AL"},
{"city":"Columbus","first_name":"Kibo","id":3,"last_name":"Horton","state":"GA"}
]
这可能吗?
答案 0 :(得分:1)
我目前无法访问雪花帐户,因此我对未经测试的解决方案表示歉意:(我认为您正在寻找array_construct
,您可以阅读about here
我希望类似的东西可以工作
COPY INTO @%mytable
FROM (
SELECT ARRAY_CONSTRUCT(objs)
FROM (
SELECT OBJECT_CONSTRUCT(
'id', id, 'first_name', first_name,
'last_name', last_name, 'city', city, 'state', state
) as objs FROM mytable
)
)
FILE_FORMAT = (TYPE = JSON);
答案 1 :(得分:1)
我不认为今天有一个很好的解决方案。
如果您的数据集很小,则@tgo的答案将起作用。但是,如果很大,创建的数组将超过16MB的雪花限制,查询将失败。
我讨厌提出建议,但是如果您真的需要此功能,只需自己构造JSON,类似
COPY INTO @%mytable FROM (
SELECT '['
UNION ALL
SELECT TO_JSON(OBJECT_CONSTRUCT(
'id', id, 'first_name', first_name,
'last_name', last_name, 'city', city, 'state', state
))
|| ','
as objs FROM mytable
UNION ALL
SELECT ']'
)
FILE_FORMAT = (TYPE = CSV)
一个陷阱是,结果JSON的最后一行的末尾将有一个结尾的,
-取决于您解析它的方式,它是否起作用。如果没有,您可以插入一个额外的尾随值,例如null
,如果没有问题。