我正在从 Bigquery 生成 .json 文件输出,并尝试仅在“属性”数组/结构中包含非空值。我的下面的查询生成 STRUCT 字段,其中包含所有值(包括 NULL)。
WITH t0 AS (
SELECT 'd1' AS product_code, 'AA|BB' AS f1, '11|22|33' AS f2, NULL AS f3
UNION ALL
SELECT 'd2' AS product_code, 'ZZ' AS f1, '55|66' AS f2, 1 AS f3
)
,t1 AS (
SELECT
product_code
,SPLIT(f1, '|') AS f1
,SPLIT(f2, '|') AS f2
,f3
FROM t0
)
SELECT
product_code
,STRUCT(f1, f2, f3) AS attributes --IGNORE NULLS ?
FROM t1
查询返回json:
[
{
"product_code": "d1",
"attributes": {
"f1": [
"AA",
"BB"
],
"f2": [
"11",
"22",
"33"
],
"f3": null
}
},
{
"product_code": "d2",
"attributes": {
"f1": [
"ZZ"
],
"f2": [
"55",
"66"
],
"f3": "1"
}
}
]
如何从
f3
数组 (d1
) 中删除 null
但将其保留在 d2
之内?
尝试复制您的问题,但没有直接的方法可以从 Bigquery 中的 d1 数组中删除 f3。作为替代方案,您可以参考这个SOpost,它使用node.js从JSON对象中删除空值。您可以将此 JSON 解析器应用于 Bigquery 的查询返回(JSON 格式)。
使用 JavaScript UDF 输出 JSON(不带空值),如下所示:
CREATE TEMP FUNCTION
stripNulls(input JSON)
RETURNS JSON
LANGUAGE js AS r"""
return Object.keys(input).reduce((output, key) => {
const value = input[key];
return value !== null ? {...output, [key]: value} : output;
}, {});
""";
SELECT stripNulls(TO_JSON(STRUCT('a' AS foo, 'b' AS bar, NULL AS biz)));
--> {"bar":"b","foo":"a"}
2023 年更新:
尝试JSON_STRIP_NULLS函数:
SELECT JSON_STRIP_NULLS(JSON '{"a": null, "b": "c"}') AS json_data
/*-----------*
| json_data |
+-----------+
| {"b":"c"} |
*-----------*/