BigQuery 中的 json 结构

Dav*_*542 1 sql google-bigquery

如果我有以下 json:

[
    {
      "Source": "Internet Movie Database",
      "Value": "7.8/10"
    },
    {
      "Source": "Rotten Tomatoes",
      "Value": "89%"
    },
    {
      "Source": "Metacritic",
      "Value": "75/100"
    }
]
Run Code Online (Sandbox Code Playgroud)

有没有办法让 BQ 能够将其插入为结构体?即,从下面看,它将是:

/* relaxed 'tuple' syntax: */
[('Internet Movie Database', '7.8/10'), ...]

/* 'full' syntax: */
[
    STRUCT('Internet Movie Database' as Source, '7.8/10' as Value),
    STRUCT('Rotten Tomatoes' as Source, '89%' as Value),
    STRUCT('Metacritic' as Source, '75/100' as Value)
] as Reviews
Run Code Online (Sandbox Code Playgroud)

Mik*_*ant 7

以下是 BigQuery 标准 SQL

#standardSQL
select 
  array(
    select as struct
      json_extract_scalar(rec, '$.Source') as Source, 
      json_extract_scalar(rec, '$.Value') as Value 
    from t.arr as rec
  ) as Reviews
from `project.dataset.table`, 
unnest([struct(json_extract_array(json) as arr)]) t   
Run Code Online (Sandbox Code Playgroud)

如果应用于您问题中的样本数据 - 输出为

在此输入图像描述

您可以使用下面的 CTE 来测试上面的内容

with `project.dataset.table` as (
  select '''
  [
      {
        "Source": "Internet Movie Database",
        "Value": "7.8/10"
      },
      {
        "Source": "Rotten Tomatoes",
        "Value": "89%"
      },
      {
        "Source": "Metacritic",
        "Value": "75/100"
      }
  ]
  ''' json
)
Run Code Online (Sandbox Code Playgroud)