【问题标题】:How to add null in ARRAY in BigQuery如何在 BigQuery 中的 ARRAY 中添加 null
【发布时间】:2021-06-26 20:42:22
【问题描述】:

我正在尝试从 BigQuery 表中的 JSON 对象中提取值。 问题陈述-我在其中一列中有一个带有 json 值的表。当键的值是数组并且数组具有匹配的值时,我想从 json 中提取值。根据下面编写的查询中给出的 where 条件,输出应该在 ARRAY 中,当有对象时,它应该在 STRING 中返回值。请参考下面的输出表和查询。 我有一张如下表

  json    
 -------- 
 "fruit":[{"apples":"5","oranges":"10"},{"apples":"5","oranges":"4"}] 
 "fruit":{"apples":"1","oranges":"15"}   
 "fruit":{"apples":"5","oranges":"1"}  
 "fruit":[{"lettuce":"7","kale": "8"}] 

我在下面写查询

选择 json, ( 选择 数组(JSON_EXTRACT_SCALAR(水果, '$.oranges')) 从 UNNEST(ifnull(json_extract_array(json, '$.fruit'), [json_EXTRACT(json, '$.fruit')])) 水果 在哪里 JSON_EXTRACT_SCALAR(水果, '$.apples') = "5") ASfruit_value 从 表格

它会给出类似Array cannot have a null element; error in writing field fruit_value 的错误 我想要如下所示的输出

|  json.   | fruit_value|  
| -------- | -------- | 
| "fruit":[{"apples":"5","oranges":"10"},{"apples":"5","oranges":"4"}]| [10,4]| 
| "fruit":{"apples":"1","oranges":"15"}| null| 
| "fruit":{"apples":"5","oranges":"1"}| 1 | 
| "fruit":[{"lettuce":"7","kale": "8"}]| null|

【问题讨论】:

    标签: json google-cloud-platform google-bigquery


    【解决方案1】:

    考虑下面

    #standardSQL
    select json,
      array(
        select json_extract_scalar(x, '$.oranges') oranges,
        from unnest(ifnull(json_extract_array(json, '$.fruit'), 
        [json_extract(json, '$.fruit')])) x  
        where json_extract_scalar(x, '$.apples') = '5'
      ) as fruit_value
    from `project.dataset.table`     
    

    如果应用于您问题中的样本数据

    with `project.dataset.table` as (
      select '{"fruit":[{"apples":"5","oranges":"10"},{"apples":"5","oranges":"4"}]}' json union all
      select '{"fruit":{"apples":"1","oranges":"15"}}' union all
      select '{"fruit":{"apples":"5","oranges":"1"}}' union all
      select '{"fruit":[{"lettuce":"7","kale": "8"}]}' 
    )     
    

    输出是

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 2021-06-21
      • 2016-09-04
      • 2020-05-23
      • 2020-12-09
      • 1970-01-01
      • 2021-06-23
      • 2021-03-22
      相关资源
      最近更新 更多