fetch key value pairs from array objects in sql BigQuery

牧云@^-^@ 提交于 2021-02-11 12:54:47

问题


I need to parse the column mapping and fetch the key value pairs from the second object in array. I would like to create new columns with the fetched data. The data looks like this:

row                 mapping 
1       [{'adUnitCode': ca, 'id': 35, 'name': ca}, {'adUnitCode': hd, 'id': 11, 'name': HD}]
2       [{'adUnitCode': bb, 'id': 56, 'name': jk}, {'adUnitCode': hm, 'id': 12, 'name': HM}]
3       [{'adUnitCode': gh, 'id': 78, 'name': ff}, {'adUnitCode': hk, 'id': 13, 'name': HK}]

The desired output:

row                 adUnitCode                  id                  name
1                     hd                       11                     HD
2                     hm                       12                     HM
3                     hk                       13                     HK

回答1:


Below is one of the approaches (BigQuery Standard SQL)

#standardSQL
select 
  json_extract_scalar(second_object, "$.adUnitCode") as adUnitCode,
  json_extract_scalar(second_object, "$.id") as id,
  json_extract_scalar(second_object, "$.name") as name
from `project.dataset.table`, unnest(
  [json_extract_array(regexp_replace(mapping, r"(: )(\w+)(,|})", "\\1'\\2'\\3"))[safe_offset(1)]]
) as second_object

if to apply above to sample data from your question - result is



来源:https://stackoverflow.com/questions/64322296/fetch-key-value-pairs-from-array-objects-in-sql-bigquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!