繁体   English   中英

Bigquery STRUCT ARRAY IGNORE NULLS TO JSON

[英]Bigquery STRUCT ARRAY IGNORE NULLS TO JSON

我正在从 Bigquery 生成 a.json 文件 output 并尝试在“属性”数组/结构中仅包含 NON NULL 值。 我的以下查询生成了包含所有值(包括 NULL)的 STRUCT 字段。

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"
    }
  }
]

如何从d1数组 ( null ) 中删除f3但将其保留在d2中?

试图复制您的问题,但没有直接的方法从 Bigquery 中的 d1 数组中删除 f3。 作为替代方案,您可以参考此 SO帖子,它使用 node.js 从 JSON object 中删除 null 个值。您可以将此 JSON 解析器应用于来自 Bigquery 的查询返回(JSON 格式)。

使用 JavaScript UDF 到 output 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"}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM