简体   繁体   English

如何为 json 查询中的每个键值对创建单独的列

[英]How to create a separate column for each key-value pair in json query

I have a json string in this format:我有一个 json 这种格式的字符串:

{"key1":
 {"key1.1":val, "key1.2":val, ...},
"key2":
 {"key2.1":val, "key2.2":val, ...}}

I am looking for a way to query this string and extract every base key-value pair as a column.我正在寻找一种方法来查询此字符串并将每个基本键值对提取为一列。 So the expected result would look something like:所以预期的结果看起来像:

Row  key1.1   key1.2  ....  key2.1   key2.2  ....
1    val      val           val      val   
2    val      val           val      val

One method would be to use JSON_VALUE for each key, but I am trying to find a more efficient method that can be applied to any JSON string.一种方法是对每个键使用 JSON_VALUE,但我试图找到一种更有效的方法,可以应用于任何 JSON 字符串。 I have thought about using a LOOP method, but not sure how to iterate over each key-value pair in a json string in bigquery.我考虑过使用 LOOP 方法,但不确定如何在 bigquery 中迭代 json 字符串中的每个键值对。

Consider below考虑以下

create temp function  extract_keys(input string) returns array<string> language js as """
  return Object.keys(JSON.parse(input));
  """;
create temp function  extract_values(input string) returns array<string> language js as """
  return Object.values(JSON.parse(input));
  """;
create temp function extract_all_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 flatten_table as 
  select json, offset, key, value
  from your_table, 
  unnest([struct(extract_all_leaves(json) as kv)]),
  unnest(extract_keys(kv)) as key with offset
  join unnest(extract_values(kv)) as value with offset
  using(offset);

execute immediate (select '''
  select * except(json) from (select * except(offset) from flatten_table)
  pivot (any_value(value) for replace(key, '.', '_') in (''' || keys_list || '''
  ))'''
from (select string_agg('"' || replace(key, '.', '_') || '"', ',' order by offset) keys_list from (
  select key, min(offset) as offset from flatten_table group by key
))
);            

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

create temp table your_table as (
  select '''{
    "key1": {"key1.1":"val11", "key1.2":"val12"}, 
    "key2": {"key2.1":"val21", "key2.2":"val22"}
  }''' json
);            

output is output 是

在此处输入图像描述

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

相关问题 BASH和jq访问JSON键值对 - BASH and jq to access JSON key-value pair 如何使用(与物化视图兼容)SQL 从具有多个键值列表的 JSON 中提取值作为列? - How to extract a value as a column from JSON with multiple key-value lists using (a materialized view compatible) SQL? 如何删除 firestore 上的键值对? (不只是价值或关键两者) - how to delete key-value pair on firestore? (not just value or key both of them) Cosmos DB 键值对查询 - Cosmos DB query on key-value pairs Amazon Textract - 如何定义我的键值对 - Amazon Textract - How to define my key-value pairs 如何将嵌套的 json 列解析为名为键和值的两列 - How to Parse nested json column to two columns called key and value 使用JQ从预过滤的JSON中提取键值对数组 - Extract an array of key-value pairs using JQ and from pre-filtered JSON 如何在redshift中解析带有键值对的字符串 - How to parse string with key value pair inside in redshift 如何从键创建新列:大查询中的值对? - How to create new columns from key: value pairs in big query? 如何使用 Databricks Notebook 从 Key:Value Pair 中提取值 - How to pull out value from Key:Value Pair with Databricks Notebook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM