大查询嵌套json字符串到数组然后新表

ef1yzkbh  于 2023-01-18  发布在  其他
关注(0)|答案(1)|浏览(132)

Bigquery数据库

我有一个webhook正在推到我的大查询表中。问题是它有很多嵌套的json字符串,这些字符串是作为字符串引入的。我最终想把这些json字符串的每一列都放到它们自己的表中,但是我被卡住了,因为我不知道如何把它们取消嵌套并放到一个数组中。

[{"id":"63bddc8cfe21ec002d26b7f4","description":"General Admission", "src_currency":"USD","src_price":50.0,"src_fee":0.0,"src_commission":1.79,"src_discount":0.0,"applicable_pass_id":null,"seats_label":null,"seats_section_label":null,"seats_parent_type":null,"seats_parent_label":null,"seats_self_type":null,
"seats_self_label":null,"rate_type":"Rate","option_name":null,"price_level_id":null,"src_discount_price":50.0,"rate_id":"636d6d5cea8c6000222c640d","cost_item_id":"63bddc8cfe21ec002d26b7f4"}]

这是original source返回的示例,下面是我正在处理的内容的屏幕截图。
[当前数据库

我尝试了很多方法,但是多重嵌套和字符串到数组的问题确实阻碍了我所尝试的一切。
老实说,我不确定什么样的输出/结构最适合这个数据集,我假设每个json返回可能只是需要是它自己的表,我可以根据json字符串中的第一个“id”值引用或连接它们,但我非常愿意接受建议。

eyh26e7m

eyh26e7m1#

您可以使用JSON函数和数组函数的组合来操作这种数据。
JSON_EXTRACT_ARRAY可以将JSON格式的字符串转换为一个数组,然后UNNEST可以将每个条目转换为行,最后JSON_EXTRACT_SCALAR可以取出单独的列。
所以这里有一个例子,我认为你正在努力实现:

with sampledata as (
  select """[{"id":"63bddc8cfe21ec002d26b7f4","description":"General Admission", "src_currency":"USD","src_price":50.0,"src_fee":0.0,"src_commission":1.79,"src_discount":0.0,"applicable_pass_id":null,"seats_label":null,"seats_section_label":null,"seats_parent_type":null,"seats_parent_label":null,"seats_self_type":null,"seats_self_label":null,"rate_type":"Rate","option_name":null,"price_level_id":null,"src_discount_price":50.0,"rate_id":"636d6d5cea8c6000222c640d","cost_item_id":"63bddc8cfe21ec002d26b7f4"},{"id":"63bddc8cfe21ec002d26b7f4","description":"General Admission", "src_currency":"USD","src_price":50.0,"src_fee":0.0,"src_commission":1.79,"src_discount":0.0,"applicable_pass_id":null,"seats_label":null,"seats_section_label":null,"seats_parent_type":null,"seats_parent_label":null,"seats_self_type":null,"seats_self_label":null,"rate_type":"Rate","option_name":null,"price_level_id":null,"src_discount_price":50.0,"rate_id":"636d6d5cea8c6000222c640d","cost_item_id":"63bddc8cfe21ec002d26b7f4"}]""" as my_json_string
)
select JSON_EXTRACT_SCALAR(f,'$.id') as id, JSON_EXTRACT_SCALAR(f,'$.rate_type') as rate_type, JSON_EXTRACT_SCALAR(f,'$.cost_item_id') as cost_item_id
from sampledata, UNNEST(JSON_EXTRACT_ARRAY(my_json_string)) as f

它根据该数据创建具有特定列的行,如下所示:

相关问题