【问题标题】:Google Big Query - Extract keys from JSON string that are not explicitly marked as keysGoogle Big Query - 从 JSON 字符串中提取未明确标记为键的键
【发布时间】:2022-01-23 00:00:40
【问题描述】:

我有以下 JSON 字符串(我为可见性添加了换行符,在实际代码中,所有这些都被压缩在一行中)

    {"schema":
       {"properties":
          {"key_1":{"label":"key 1","type":"string"},
           "key_2":{"label":"key 2","type":"string"},
           "ley_3":{"label":"key 3","type":"string"},
           "key_4":{"label":"key 4","type":"string"},
           ...
          } 
       }
    }

我要做的是提取与该键关联的所有键和标签。我知道how to do this when key is explicitly stated in JSON,但在此示例中未明确说明密钥。

我关注Google Big Query documentation 处理 JSON 字符串,以下是我的进展:

SELECT json_schema, JSON_EXTRACT(json_schema, "$.schema.properties"), JSON_EXTRACT(json_schema, "$.schema.properties[1]")
FROM schemas

json_schemaschemas 表中的列名。

这让我找到了正确的方向,但我不知道如何从这里开始。我想要的输出是(例如),是:

key    value
key_1  key 1
key_2  key 2
key_3  key 3
key_4  key 4

这里是重现示例的代码:

SELECT '{"schema":{"properties":{"key_1":{"label":"key 1","type":"string"},"key_2":{"label":"key 2","type":"string"},"key_3":{"label":"key 3","type":"string"},"key 4":{"label":"key_4","type":"string"}}}}' AS json_schema

【问题讨论】:

    标签: sql json google-bigquery


    【解决方案1】:

    考虑以下方法

    select key, 
      json_extract_scalar(regexp_extract(props, r'"' || key || '":({.*?})'), '$.label') value
    from your_table, 
    unnest([struct(json_extract(json_schema, '$.schema.properties') as props)]),
    unnest(`bqutil.fn.json_extract_keys`(props)) key 
    
           
    

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

    with your_table as (
       select '''
        {"schema":
           {"properties":
              {"key_1":{"label":"key 1","type":"string"},
               "key_2":{"label":"key 2","type":"string"},
               "ley_3":{"label":"key 3","type":"string"},
               "key_4":{"label":"key 4","type":"string"}
              } 
           }
        }
       ''' json_schema
    )              
    

    输出是

    【讨论】:

    • 感谢米哈伊尔的回答。我现在 AFK 并将对此进行分析以确保我理解代码中的所有内容。一旦我确认这可行并且对我有意义,我会很高兴地投票:握手:
    • 米哈伊尔,我正在努力实施您提出的解决方案。当我在我提供的示例中使用您的解决方案时,它运行良好。当我将此应用于我的实际数据时,我收到以下错误消息Regular expressions passed into extraction functions must not have more than 1 capturing group。如果我提供一个我正在使用的完整示例,会有帮助吗?
    • 我回答了您的原始问题并且它有效,因此我建议您发布包含所有相关详细信息和正确/真实输入数据以及所需逻辑/输出的新问题。同时考虑对答案进行投票并接受它
    • 很高兴地接受了这个作为首选答案并投了赞成票。如果您认为该问题有帮助且格式正确,请考虑支持该问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2021-02-16
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多