Google Big Query 检查 json 键是不是存在
Posted
技术标签:
【中文标题】Google Big Query 检查 json 键是不是存在【英文标题】:Google Big Query check if json key existsGoogle Big Query 检查 json 键是否存在 【发布时间】:2020-02-27 10:31:53 【问题描述】:我有一个 Google Big Query Table 列,其中包含一个 json 字符串。随着时间的推移,新的键被引入到这个 json 字符串中。
time col_b
--------------------------------------------------
timestamp3 "key1": "value", "key2": "value"
timestamp2 "key1": "value"
timestamp1 "key1": "value"
如何提取 key2 并在它不存在的情况下用 NaN 填充? 我想到了类似的东西:
SELECT
JSON_EXTRACT(col_b, "$.key2) AS key2
FROM db;
这样做会抛出错误,因此它认为它应该是一个双精度值而不是空值的字符串原因。
Bad double type: value
如何提前检查key2是否存在,如果不存在则填空?
【问题讨论】:
【参考方案1】:见下例
#standardSQL
WITH `project.dataset.table` AS (
SELECT 'timestamp3' time, '"key1": "value", "key2": "value"' col_b UNION ALL
SELECT 'timestamp2', '"key1": "value"' UNION ALL
SELECT 'timestamp1', '"key1": "value"'
)
SELECT *, IFNULL(JSON_EXTRACT_SCALAR(col_b, '$.key2'), 'NaN') AS key2
FROM `project.dataset.table`
有输出
Row time col_b key2
1 timestamp3 "key1": "value", "key2": "value" value
2 timestamp2 "key1": "value" NaN
3 timestamp1 "key1": "value" NaN
【讨论】:
【参考方案2】:有类似的问题,但正在寻找一个可以为空的密钥,并且如果 key 存在,尽管它是空的,但对它很感兴趣。 我发现上面的例子在我的具体情况下是不正确的,下面是我的例子——希望有人会觉得它有用。
#standardSQL
CREATE TEMPORARY FUNCTION
jsonHasKey(libs STRING, key STRING)
RETURNS BOOL
LANGUAGE js AS '''
try
x = JSON.parse(libs);
return x.hasOwnProperty(key);
catch (e)
return false;
''';
WITH `project.dataset.table` AS (
SELECT 'timestamp3' time, '"key1": "value", "key2": "value"' col_b UNION ALL
SELECT 'timestamp2', '"key1": "value"' UNION ALL
SELECT 'timestamp1', '"key1": "value"' UNION ALL
SELECT 'timestamp0', '"key1": "value", "key2": null'
)
SELECT *, IFNULL(JSON_EXTRACT_SCALAR(col_b, '$.key2'), 'NaN') AS key2, jsonHasKey(col_b, 'key2') AS is_present
FROM `project.dataset.table`
产生以下结果:
time col_b key2 is_present
timestamp3 """key1"": ""value"", ""key2"": ""value""" value true
timestamp2 """key1"": ""value""" NaN false
timestamp1 """key1"": ""value""" NaN false
timestamp0 """key1"": ""value"", ""key2"": null" NaN true
【讨论】:
以上是关于Google Big Query 检查 json 键是不是存在的主要内容,如果未能解决你的问题,请参考以下文章
在 Google Big Query 中将两个数组连接在一起