【问题标题】:How to use JSON_EXTRACT without having a key name?如何在没有键名的情况下使用 JSON_EXTRACT?
【发布时间】:2021-07-24 04:39:58
【问题描述】:

如何在 google bigquery 中使用 JSON_EXTRACT 从 JSON 中提取值 frm 键“Nome”? 我不能在查询中使用键 135,因为它是动态的(例如 JSON_EXTRACT(vista, '$.Agencia.135.Nome'))

如何在没有键 '135' 名称的情况下使用 JSON_EXTRACT?

JSON 记录示例:

{
    "Campanha": "Campanha A",
    "Ad": "Ad A",
    "Agencia": {
        "135": {
            "Celular": ".",
            "Codigo": "135",
            "CodigoPai": "105",
            "DDD": "00",
            "Email": "email-A@email.com",
            "Nome": "Nome A",
            "Fone": "00 0000.0000",
            "Fone2": ".",
            "Foto": "foto-A.jpg" 
        }
    }
}

【问题讨论】:

    标签: google-bigquery


    【解决方案1】:

    不确定您的 json 格式是否正确。键'135'是一个数组吗?如果是这样,请正确格式化,您可以按照以下示例访问它:

    SELECT JSON_EXTRACT(json_text, '$.Agencia.135[1]') AS  nome
    FROM UNNEST([
        '{"Agencia":{"135":[{"Codigo":"135"},{"Nome":"Nome A"}]}}'
    ]) AS json_text;
    

    这会给你:

    [
      {
        "nome": "{\"Nome\":\"Nome A\"}"
      }
    ]
    

    有关 JSON_EXTRACT 的更多参考:https://cloud.google.com/bigquery/docs/reference/standard-sql/json_functions#json_extract

    【讨论】:

      【解决方案2】:

      使用下面的方法

      execute immediate (
          select string_agg("select " || key || ''' key
          , JSON_EXTRACT_SCALAR(vista, '$.Agencia.''' || key || '''.Nome') AS Nome 
        from `project.dataset.table`''', " union all ")
        from `project.dataset.table`, unnest(regexp_extract_all(regexp_replace(JSON_EXTRACT(vista, '$.Agencia'), r':{.*?}+', ''), r'"(.*?)"')) key
      );
      

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

      另外,取决于您的用例 - 您也可以尝试以下选项

      execute immediate (
          select 'select * from (' || string_agg("select " || key || ''' key
          , JSON_EXTRACT_SCALAR(vista, '$.Agencia.''' || key || '''.Nome') AS Nome 
        from `project.dataset.table`''', " union all ") || ') where not Nome is null'
        from `project.dataset.table`, unnest(regexp_extract_all(regexp_replace(JSON_EXTRACT(vista, '$.Agencia'), r':{.*?}+', ''), r'"(.*?)"')) key
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-30
        • 2020-09-17
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 2019-11-15
        相关资源
        最近更新 更多