我正在尝试从json中提取每个json中的两个密钥(使用sql legacy) 目前我正在使用json提取功能:
json_extract(json_column , '$[1].X') AS X,
json_extract(json_column , '$[1].Y') AS Y,
我怎样才能使其在“ json arry arry column”的每个json上运行,而不仅仅是[1](例如)?
一个示例json:
[
{"blabla":000,"X":1,"blabla":000,"blabla":000,"blabla":000,,"Y":"2"},
{"blabla":000,"X":3,"blabla":000,"blabla":000,"blabla":000,,"Y":"4"},
]
提前谢谢!
答案 0 :(得分:5)
让我们从一个类似的问题开始-这不是从json数组提取所有电子邮件的便捷方法:
SELECT id
, [ JSON_EXTRACT_SCALAR(JSON_EXTRACT(payload, '$.commits'), '$[0].author.email')
, JSON_EXTRACT_SCALAR(JSON_EXTRACT(payload, '$.commits'), '$[1].author.email')
, JSON_EXTRACT_SCALAR(JSON_EXTRACT(payload, '$.commits'), '$[2].author.email')
, JSON_EXTRACT_SCALAR(JSON_EXTRACT(payload, '$.commits'), '$[3].author.email')
] emails
FROM `githubarchive.day.20180830`
WHERE type='PushEvent'
AND id='8188163772'
我们现在要解决的最佳方法是在UDF中使用一些JavaScript将json数组拆分为SQL数组:
CREATE TEMP FUNCTION json2array(json STRING)
RETURNS ARRAY<STRING>
LANGUAGE js AS """
return JSON.parse(json).map(x=>JSON.stringify(x));
""";
SELECT * EXCEPT(array_commits),
ARRAY(SELECT JSON_EXTRACT_SCALAR(x, '$.author.email') FROM UNNEST(array_commits) x) emails
FROM (
SELECT id
, json2array(JSON_EXTRACT(payload, '$.commits')) array_commits
FROM `githubarchive.day.20180830`
WHERE type='PushEvent'
AND id='8188163772'
)
答案 1 :(得分:2)
下面是BigQuery标准SQL的示例,它使您可以接近使用JSONPath的标准方式,并且不需要额外的操作,因此您只需使用CUSTOM_JSON_EXTRACT(json, json_path)
函数
#standardSQL
CREATE TEMPORARY FUNCTION CUSTOM_JSON_EXTRACT(json STRING, json_path STRING)
RETURNS ARRAY<STRING>
LANGUAGE js AS """
return jsonPath(JSON.parse(json), json_path);
"""
OPTIONS (
library="gs://your_bucket/jsonpath-0.8.0.js"
);
WITH t AS (
SELECT '''
[
{"blabla1":1,"X":1,"blabla2":3,"blabla3":5,"blabla4":7,"Y":"2"},
{"blabla1":2,"X":3,"blabla2":4,"blabla3":6,"blabla4":8,"Y":"4"}
]
''' AS json_column
)
SELECT
CUSTOM_JSON_EXTRACT(json_column , '$[*].X') AS X,
CUSTOM_JSON_EXTRACT(json_column , '$[*].Y') AS Y
FROM t
结果将是
Row X Y
1 1 2
3 4
注意:为克服当前BigQuery对JsonPath的“限制”,上述解决方案使用custom function和external library-jsonpath-0.8.0.js
,可以从https://code.google.com/archive/p/jsonpath/downloads下载并上传到Google云端存储-gs://your_bucket/jsonpath-0.8.0.js
只需重新阅读Felipe的答案-对于他上面的示例,解决方案将如下所示(仅供参考)
SELECT
id,
CUSTOM_JSON_EXTRACT(payload, '$.commits[*].author.email') emails
FROM `githubarchive.day.20180830`
WHERE type='PushEvent'
AND id='8188163772'