[英]BigQuery JSON element extraction
我在 BigQuery 中有一个表,其中包含 JSON 列,请参见下文。
文件编号 | 数据 |
---|---|
222 | {...} |
333 | {...} |
数据 JSON 列看起来 ID 设置为标题。
{
"1675223776617": {
"author": "aaa",
"new": "2023-02-01",
"old": null,
"property": "asd",
"sender": "wew"
},
"1675223776618": {
"author": "aaa",
"new": true,
"old": null,
"property": "asd",
"sender": "ewew"
},
"1675223776619": {
"author": "bbb",
"new": "ySk2btk7",
"old": null,
"property": "qwe",
"sender": "yyy"
}
}
我想在 BigQuery 中使用 SQL 将这个 JSON 提取成这种格式。
请注意,header
id
未在 JSON 中定义。
文件编号 | ID | 作者 | 新的 | 老的 | 财产 | 发件人 |
---|---|---|---|---|---|---|
222 | 1675223776617 | 啊啊 | 2023-02-01 | null | ASD | 哇 |
222 | 1675223776618 | 啊啊 | 真的 | null | ASD | 母狼 |
222 | 1675223776619 | bbb | ySk2btk7 | null | qwe | yyy |
我尝试使用 JSON_EXTRACT function 但没有成功。
您可以考虑使用以下方法使用 javascript UDF。
CREATE TEMP FUNCTION flatten_json(json STRING)
RETURNS ARRAY<STRUCT<id STRING, author STRING, new STRING, old STRING, property STRING, sender STRING>>
LANGUAGE js AS """
result = [];
for (const [key, value] of Object.entries(JSON.parse(json))) {
value["id"] = key; result.push(value);
}
return result;
""";
WITH sample_table AS (
SELECT 222 doc_id, '''{
"1675223776617": {
"author": "aaa",
"new": "2023-02-01",
"old": null,
"property": "asd",
"sender": "wew"
},
"1675223776618": {
"author": "aaa",
"new": true,
"old": null,
"property": "asd",
"sender": "ewew"
},
"1675223776619": {
"author": "bbb",
"new": "ySk2btk7",
"old": null,
"property": "qwe",
"sender": "yyy"
}
}''' data
)
SELECT doc_id, flattened.*
FROM sample_table, UNNEST(flatten_json(json)) flattened;
查询结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.