首页 > 解决方案 > Bigquery - json_array 来自字段的额外多个元素

问题描述

我的表有一个 JSON 字段,看起来像这样。每个条目中可以有任意数量的评论。

{
    "entry": 1234,
    "comment_6789": {
        "_seconds": 1614864327,
        "_nanoseconds": 606000000,
        "message": "hello world"
    },
    "comment_4564564": {
        "_seconds": 1614864327,
        "_nanoseconds": 606000000,
        "message": "hello mars"
    }
}

阅读此问题后,我知道我可以使用 JSON_EXTRACT_ARRAY,但我有点不确定如何定位每个comment_条目,因为它们会有不同的 id?

标签: sqlarraysjsongoogle-bigquery

解决方案


考虑下面

#standardSQL
with `project.dataset.table` as (
  select 1 id, '''
  {
    "entry": 1234,
    "comment_6789": {
        "_seconds": 1614864327,
        "_nanoseconds": 606000000,
        "message": "hello world"
    },
    "comment_4564564": {
        "_seconds": 1614864327,
        "_nanoseconds": 606000000,
        "message": "hello mars"
    }
  }  
  '''  col
)
select id, comment,
  json_value(kv, '$._seconds') seconds,
  json_value(kv, '$._nanoseconds') nanoseconds,
  json_value(kv, '$.message') message
from `project.dataset.table`,
unnest(regexp_extract_all(col, r'comment_\d+')) comment,
unnest([struct(regexp_extract(col, r'"' || comment || '": ({[^{}]+})') as kv)])      

带输出

在此处输入图像描述


推荐阅读