如何使用JSON Extract Scalar选择数据?

时间:2018-12-14 09:11:45

标签: sql google-bigquery

我想从以下字符串中提取20230024

  

[{\“ vendorExternalId \”:\“ 459162 \”,\“ isActive \”:1,\“名称\”:\“ Strings1 \”},{\“ vendorExternalId \”:\“ 20230024 \“,\” isActive \“:1,\”名称\“:\” Strings2 \“}]]

附上我在bigquery中的查询

    select JSON_EXTRACT_SCALAR(teks,"$[vendorExternalID]") as output
from(
select "[{\"vendorExternalId\": \"459162\", \"isActive\": 1, \"name\": \"Strings1\"}, {\"vendorExternalId\": \"20230024\", \"isActive\": 1, \"name\": \"Strings2\"}]" as teks
)

我的查询返回了JSONPath parse error at: [vendorExternalID]

我该如何解决?

1 个答案:

答案 0 :(得分:1)

BigQuery JSON提取函数不支持*(星号)运算符,因此无法提取数组。为此,您需要创建用户定义函数并将JSON解析为任意格式。

如您在下面的示例中看到的,这将返回

ARRAY<STRUCT<vendorExternalId INT64, isActive INT64, name STRING>>

#standardSQL
CREATE TEMPORARY FUNCTION parseJson(libs STRING)
    RETURNS ARRAY<STRUCT<vendorExternalId INT64, isActive INT64, name STRING>>
    LANGUAGE js AS """
      try {
        return JSON.parse(libs);
      } catch (e) {
        return [];
      }
    """;
SELECT parseJson('[{\"vendorExternalId\": \"459162\", \"isActive\": 1, \"name\": \"Strings1\"}, {\"vendorExternalId\": \"20230024\", \"isActive\": 1, \"name\": \"Strings2\"}]') parsed 

您可以进一步UNNEST阵列

enter image description here