简体   繁体   English

在 Big Query 中解析动态 JSON

[英]Parse a dynamic JSON in Big Query

I have a table that looks like this:我有一个看起来像这样的表: 在此处输入图像描述

And the JSON has dynamic keys and looks like this: JSON 具有动态键,如下所示:

{
key_1:{
     value_1:a
     value_2:b
     },
key_2:{
     value_1:c
     value_2:d
     }
}

I need to parse this table to get an output that looks like this:我需要解析这个表以获得一个看起来像这样的 output:

在此处输入图像描述

Tried it with JS functions but couldn't get it quite right.尝试使用 JS 函数,但无法完全正确。 Thanks in advance: )提前致谢: )

Consider below approach考虑以下方法

create temp function get_keys(input string) returns array<string> language js as """
  return Object.keys(JSON.parse(input));
  """;
create temp function get_values(input string) returns array<string> language js as """ 
  return Object.values(JSON.parse(input));
  """;
create temp function get_leaves(input string) returns string language js as '''
  function flattenObj(obj, parent = '', res = {}){
    for(let key in obj){
        let propName = parent ? parent + '.' + key : key;
        if(typeof obj[key] == 'object'){
            flattenObj(obj[key], propName, res);
        } else {
            res[propName] = obj[key];
        }
    }
    return JSON.stringify(res);
  }
  return flattenObj(JSON.parse(input));
  ''';

create temp table temp as (
  select format('%t', t) row_id, date, name, val, 
    split(key, '.')[offset(0)] as key, 
    split(key, '.')[offset(1)] as col, 
  from your_table t, unnest([struct(get_leaves(json_extract(json, '$')) as leaves)]),
  unnest(get_keys(leaves)) key with offset
  join unnest(get_values(leaves)) val with offset using(offset)
  );

execute immediate (
  select '''
    select * except(row_id) from temp
    pivot (any_value(val) for col in ("''' || string_agg(distinct col, '","') || '"))'
  from temp
);              

if applied to sample data in your question - output is如果应用于您问题中的示例数据 - output 是

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM